<?php

namespace services\common;

use common\helpers\CommonHelper;
use common\models\base\PatientDiseases;
use common\models\hospital\ProjectPrincipal;
use common\models\hospital\RegisterFee;
use common\models\marketing\CallbackStatus;
use common\models\patient\Callback;
use common\models\patient\RevisitingRecord;
use services\log\MemberOperateLogService;
use services\log\PatientOperateLogService;
use services\statistics\ManagementReportService;
use Yii;
use common\models\hospital\HistoryLog;
use common\models\hospital\InHospital;
use common\models\patient\AllocationRecord;
use common\models\patient\OperateLog;
use common\models\hospital\HospitalLog;
use common\models\clinic\RelationKefu;
use common\models\member\Member;
use common\models\base\Profession;
use common\models\hospital\CrontabLog;
use common\models\hospital\ExpenseHeader;
use common\models\hospital\RegistrationHeader;
use common\models\marketing\SourceChannel;
use common\models\clinic\Clinic;
use common\models\clinic\UserTreatmentDetail;
use common\models\clinic\UserTreatmentProject;
use common\models\common\Config;
use common\models\common\Provinces;
use common\models\marketing\OutpatientType;
use common\models\member\Attr;
use common\models\patient\Consumption;
use common\models\patient\ConsumptionDetail;
use common\models\base\Project;
use common\models\clinic\Project as clinic_project;
use common\models\patient\ClinicRecord;
use common\models\patient\User;
use PHPExcel_Exception;
use PHPExcel_Reader_Exception;
use common\models\hospital\Expense;
use common\models\hospital\ExpenseTotal;
use common\models\hospital\SectionList;
use common\models\hospital\RegistrationList;
use common\components\Service;
use common\models\hospital\DocumentList;
use PHPExcel;
use PHPExcel\IOFactory;
use yii\db\Exception;
use yii\db\Expression;
use yii\filters\AccessControl;
use yii\rest\UpdateAction;
use yii\web\HttpException;
use yii\web\RequestParserInterface;
use function GuzzleHttp\Promise\queue;
use function GuzzleHttp\Psr7\str;
use function Hprose\Future\all;


class ExcelService extends Service
{

    /**
     * @param $path excel表路径
     * @param $hospital
     * @param $time
     * @return bool
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     */

    // 项目
    public static $projectArray = [];
    // 诊疗项目
    public static $clinicProjectArray = [];
    // 奕远诊室
    public static $sectionArray = [];
    // 全局配制
    public static $configArray = [];
    // 诊室医助
    public static $clinicRoomArray = [];
    // 就诊类型
    public static $outpatientTypeArray = [];
    // 来源渠道
    public static $channelArray = [];
    // 获取客服来源
    public static $customerServiceArray = [];

    public function loadExcel($path, $hospital, $time)
    {
        ini_set("memory_limit", "-1M");
        $PHPReader = \PHPExcel_IOFactory::load($path);

        // 根据excel 名称来判断是,挂号表,还是消费详细
        $nameArray = explode('_', $path);
        $name = end($nameArray);
        $pattern = '/^money|^guahao/i';
        preg_match($pattern, $name, $matches);
        $type = end($matches);

        $sheetData = $PHPReader->getActiveSheet()->toArray(null, true, true, true);

        if ($type == 'money') {

            $data = self::patientExpense($sheetData, $hospital, $time);

            if (is_array($data)) {
                $data['type'] = DocumentList::patient_expense;//病人费用明细表
            }

            return $data;

        } else if ($type == 'guahao') {

            $data = self::registrationDocuments($sheetData, $hospital);
            if (is_array($data)) {
                $data['type'] = DocumentList::registration_list;//医院门诊挂号单据表
            }
            return $data;

        } else if ($hospital == 'cs') {
            //长沙鹏程系统专用
//            $data = self::patientCs($sheetData, $hospital);
//            if (is_array($data)) {
//                $data['type'] = DocumentList::registration_list;//医院门诊挂号单据表
//            }
//            return $data;
        }

        return false;
    }

    /**
     * @param $sheetData
     * @param $hospital
     * @return bool
     */
    public static function patientCs($sheetData, $hospital)
    {
        Expense::$pix = $hospital;
        SectionList::$pix = $hospital;

        //从第三行开始有正式数据
        $array = array_diff_key($sheetData, [1, 2]);

        $sectionInfo = SectionList::find()
            ->asArray()
            ->all();
        $sectionInfo = array_column($sectionInfo, 'id', 'section');

        $insertData = [];
        $card_id = '';
        $patient_name = '';
        $event_time = '';
        $section = '';
        $day = '';
        $doctor_name = '';
        foreach ($array as $value) {
            //快的开始
            if (!empty($value['B']) && !empty($value['C']) && !empty($value['D'])) {

                if (!isset($sectionInfo[$value['F']])) {
                    $listModel = new SectionList();
                    $listModel->section = $value['F'];
                    $listModel->save();
                    $sectionInfo = SectionList::find()
                        ->asArray()
                        ->all();
                    $sectionInfo = array_column($sectionInfo, 'id', 'section');
                }

                $card_id = $value['B'];
                $patient_name = $value['C'];
                $event_time = date('Y-m-d H:i:s', strtotime($value['E']));
                $day = date('Y-m-d', strtotime($value['E']));
                $doctor_name = $value['G'];
                $section = $sectionInfo[$value['F']];
            }

            // 合计
            if (!empty($value['B']) && empty($value['C'])) {

                $card_id = '';
                $patient_name = '';
                $event_time = '';
                $section = '';
                $day = '';
                $doctor_name = '';

            } elseif (!empty($value['H'])) {

                // 查询是不是导入过的数据
                if (Expense::find()->where(['total_md5' => $value['H']])->exists()) {
                    continue;
                }

                $insertData[] = [
                    'drug' => $value['I'],
                    'unit' => $value['J'],
                    'count' => $value['M'],
                    'sales_money' => $value['N'],
                    'price' => $value['L'],
                    'discounted_money' => $value['N'],
                    'money_name' => $value['O'],
                    'event_time' => $event_time,
                    'created_at' => time(),
                    'card_id' => $card_id,
                    'patient_name' => $patient_name,
                    'section' => $section,
                    'doctor_name' => $doctor_name,
                    'total_md5' => $value['H'],
                    'day' => strtotime($day),
                ];

            }

        }
//        print_r($insertData);die();

        $insertItem = [
            'drug', 'unit', 'count', 'sales_money', 'price', 'discounted_money', 'money_name',
            'event_time', 'created_at', 'card_id', 'patient_name', 'section', 'doctor_name', 'total_md5', 'day',
        ];

        Yii::$app->db3->createCommand()->batchInsert(Expense::tableName(), $insertItem, $insertData)->execute();

        return true;

    }

    /**
     * @param $sheetData
     * @param $hospital
     * @param $time
     * @return bool
     */
    public static function patientExpense($sheetData, $hospital, $time)
    {
        Expense::$pix = $hospital;
        SectionList::$pix = $hospital;
        $heardArray = ExpenseHeader::find()
            ->where(['hospital' => $hospital])
            ->andWhere(['status' => 1])
            ->asArray()
            ->one();

        //从第三行开始
        $array = array_diff_key($sheetData, [1, 2, 3, 4, 5]);
        $temp = [];
        $allData = [];
        $tempTotal = 0;
        //数组key-value 互换
        $businessTypeInfo = array_flip(Expense::$businessType);
        $sectionInfo = SectionList::find()
            ->asArray()
            ->all();
        $sectionInfo = array_column($sectionInfo, 'id', 'section');
        $item_count_all = 0;

        foreach ($array as $k => $v) {

            //顺序快的开始
            if (empty($v[$heardArray['business_type']]) && empty($v[$heardArray['card_id']]) && empty($v[$heardArray['patient_name']]) && empty($v[$heardArray['section']])) {
                //统计有效循环次数
                $item_count_all++;
                //单个药品记录  //拼接
                $tempTotal++;
                $v[$heardArray['discounted_money']] = empty($v[$heardArray['discounted_money']]) ? 0 : $v[$heardArray['discounted_money']];
                $v[$heardArray['buy_money']] = empty($v[$heardArray['buy_money']]) ? 0 : $v[$heardArray['buy_money']];
                $item = [
                    'drug' => $v[$heardArray['drug']],
                    'unit' => $v[$heardArray['unit']],
                    'count' => $v[$heardArray['count']],
                    'sales_money' => $v[$heardArray['sales_money']],
                    'price' => $v[$heardArray['price']],
                    'discounted_money' => $v[$heardArray['discounted_money']],
                    'buy_money' => $v[$heardArray['buy_money']] ?? 0,
                    'difference_money' => $v[$heardArray['difference_money']] ?? 0,
                    'money_name' => $v[$heardArray['money_name']],
                    'event_time' => date('Y-m-d H:i:s', strtotime($v[$heardArray['event_time']])),
                    'user_name' => $v[$heardArray['user_name']],
                    'created_at' => time(),
                ];
                $day = date('Y-m-d', strtotime($v[$heardArray['event_time']]));
                $temp[$day][] = $item;
            }

            if (!empty($v[$heardArray['business_type']]) && !empty($v[$heardArray['card_id']]) && !empty($v[$heardArray['patient_name']]) && !empty($v[$heardArray['section']])) {

                //判断门诊部门存不存在,如果不存在插入一条新数据重新
                if (!isset($sectionInfo[$v[$heardArray['section']]])) {
                    $listModel = new SectionList();
                    $listModel->section = $v[$heardArray['section']];
                    $listModel->save();
                    $sectionInfo = SectionList::find()
                        ->asArray()
                        ->all();
                    $sectionInfo = array_column($sectionInfo, 'id', 'section');
                }

                $business_type = $businessTypeInfo[$v[$heardArray['business_type']]] ?? 0;
                $card_id = $v[$heardArray['card_id']];
                $patient_name = $v[$heardArray['patient_name']];
                $section = $sectionInfo[$v[$heardArray['section']]];
                $doctor_name = $v[$heardArray['doctor_name']];

                // 如果号段是9100 开头的,直接跳过
                if (substr($card_id, 0, 4) == '9100') {
                    $temp = [];
                }

                if (!empty($v[$heardArray['section']])) {
                    // 查询最后两个字符是不是诊室,如果不是诊室,跳过为无效信息
                    if ($v[$heardArray['section']] == '住院部') {
                        continue;
                    }

                    if ($hospital == 'nc' && ($v[$heardArray['section']] == '住院部' || $v[$heardArray['section']] == '病区一')) {
                        continue;
                    }

                }

                foreach ($temp as $day => &$item) {

                    foreach ($item as &$value) {
                        $value['business_type'] = $business_type;
                        $value['card_id'] = $card_id;
                        $value['patient_name'] = $patient_name;
                        $value['section'] = $section;
                        $value['doctor_name'] = $doctor_name;
                        $value['day'] = strtotime($day);
                        $allData[$card_id][$day][] = $value;
                    }
                }
                $temp = [];
            }
            // 每处理一条数据,数组清空一条数据
            unset($array[$k]);
        }

        // 一个用户一个数组
        foreach ($allData as $card_id => $dayArray) {
            // 日期层
            foreach ($dayArray as $day => &$value) {
                // 数据根据日期升序排列
                $last_names = array_column($value, 'event_time');
                array_multisort($last_names, SORT_ASC, $value);

                // 查询该用户当天的消费记录条数
                $db_count = Expense::find()
                    ->where(['card_id' => $card_id])
                    ->andWhere(['day' => strtotime($day)])
                    ->count();
                $arrayCount = count($value);
                $count = $arrayCount - $db_count > 0 ? $arrayCount - $db_count : 0;

                // 没有需要插入的数据,直接跳过
                if ($count == 0) {
                    continue;
                }
                $insertData = array_splice($value, $arrayCount - $count, $count);
                $insertItem = [
                    'drug',
                    'unit',
                    'count',
                    'sales_money',
                    'price',
                    'discounted_money',
                    'buy_money',
                    'difference_money',
                    'money_name',
                    'event_time',
                    'user_name',
                    'created_at',
                    'business_type',
                    'card_id',
                    'patient_name',
                    'section',
                    'doctor_name',
                    'day',
                ];

                Yii::$app->db3->createCommand()->batchInsert(Expense::tableName(), $insertItem, $insertData)->execute();

            }
        }

        return true;
    }

    // 同步更新,灯塔 patient_user表,白友patient_user,patient_clinic_record,by_clinic_user_treatment_detail,by_clinic_user_treatment_project表
    public static function updateData($hospital, $day = null)
    {
        ini_set("memory_limit", "-1M");

        // 获取当天的数据
        Expense::$pix = $hospital;
        ExpenseTotal::$pix = $hospital;
        SectionList::$pix = $hospital;
        $query = Expense::find();

        $is_day = 0;
        if ($day) {
            $is_day = 1;
            $query->where(['day' => strtotime($day)]);
        }

        $allData = $query->asArray()
            ->all();

        self::allData($allData, $hospital, $is_day);

        return true;
    }

    // 同步更新,根据起始时间
    public static function updateTimeData($hospital, $startTime, $endTime, $is_day = 1)
    {
        ini_set("memory_limit", "-1M");

        // 获取当天的数据
        Expense::$pix = $hospital;
        ExpenseTotal::$pix = $hospital;
        SectionList::$pix = $hospital;
        $query = Expense::find();

        $query->where(['between', 'day', strtotime($startTime), strtotime($endTime)]);

        $allData = $query->asArray()
            ->all();

        self::allData($allData, $hospital, $is_day);

        return true;
    }

    /**
     *
     * @param $allData
     * @param $hospital
     * @param $type  type = 1 逐条处理  type = 2 统一处理
     */
    public static function allData($allData, $hospital, $type)
    {
        if ($type == 1) {

            // 更新治疗项目信息
            //    self::updateTreatment($allData,$hospital);

            // 消费记录
            //    self::updateExpenseRecord($allData,$hospital);
            // 更新用户到诊记录
            //   self::recordDeal($allData,$hospital);
            // 更新消费详细表
            self::updateConsumption($allData, $hospital);

        } elseif ($type == 2) {
            // 更新治疗项目信息
            //      self::all_updateTreatment($allData,$hospital);
            // 更新用户到诊记录
            //    self::all_recordDeal($allData,$hospital);
            // 更新消费详细表
            self::all_updateConsumption($allData, $hospital);

        }
    }

    /**
     * 通过where 筛选条件来获取载入内容
     * @param $hospital
     * @param $type
     * @param $where
     * @return bool
     */
    public static function whereData($hospital, $type, $where)
    {
        ini_set("memory_limit", "-1M");

        // 获取当天的数据
        Expense::$pix = $hospital;

        $sql = 'select *from ' . Expense::tableName() . 'where ' . $where;

        $allData = Yii::$app->db3->createCommand($sql)->queryAll();

        self::allData($allData, $hospital, $type);

        return true;
    }

    /**
     * 更新药品消费记录表/合计表
     * @param $data
     * @param $hospital
     * @throws HttpException
     */
    public static function updateConsumption($data, $hospital)
    {
        // 判断数据有没有同步到
        foreach ($data as $value) {
            // 跳过已经导入过的数据
            $exists = ConsumptionDetail::find()
                ->where(['yiyuan_aid' => $value['id']])
                ->andWhere(['project_id' => self::getProject($hospital)])
                ->exists();

            if ($exists) {
                continue;
            }

            $transaction = Yii::$app->db->beginTransaction();
            try {
                // 查询有没有当次的汇总信息
                $model = Consumption::find()
                    ->where(['and',
                        ['patient_card_id' => $value['card_id']],
                        ['project_id' => self::getProject($hospital)],
                        ['clinic_time' => strtotime($value['event_time'])],
                    ])
                    ->one();

                if (!$model) {
                    $model = new Consumption();
                    $model->clinic_time = strtotime($value['event_time']);
                    $model->project_id = self::getProject($hospital);
                    $model->patient_card_id = $value['card_id'];
                    $model->consulting_room = self::getSection($value['section'], $hospital, 'clinic_name');
                    $model->clinic_id = self::getSection($value['section'], $hospital, 'clinic_id');
                    $model->doctor_name = $value['doctor_name'];
                    $model->money = 0;
                    $model->refund_money = 0;
                }

                // 计算实收金额
                $discounted_money = $value['discounted_money'];

                if ($discounted_money > 0) {
                    $model->money += $discounted_money;
                } elseif ($discounted_money < 0) {
                    $model->refund_money += $discounted_money;
                }
                $model->reality_money += $discounted_money;
                $model->trade_type = $model->reality_money > 0 ? Consumption::TRADE_TYPE_BOOKED : Consumption::TRADE_TYPE_REFUND;
                $model->save();

                $detailModel = new ConsumptionDetail();
                $detailModel->yiyuan_aid = $value['id'];
                $detailModel->consumption_id = $model->id;
                $detailModel->project_id = self::getProject($hospital);
                $detailModel->patient_card_id = $value['card_id'];
                $detailModel->drug_name = $value['drug'] ?? '';
                $detailModel->drug_num = $value['count'];
                $detailModel->drug_unit = $value['unit'];
                $detailModel->drug_type = $value['money_name'];
                $detailModel->price = $value['price'];
                $detailModel->money = $value['sales_money'];
                $detailModel->reality_money = $value['discounted_money'];
                $detailModel->consumption_type = $value['discounted_money'] > 0 ? ConsumptionDetail::CONSUMPTION_TYPE_BOOKED : ConsumptionDetail::CONSUMPTION_TYPE_REFUND;

                if ($value['sales_money'] != 0) {
                    $detailModel->discount_rate = $value['discounted_money'] / $value['sales_money'];
                }
                $detailModel->event_at = strtotime($value['event_time']);
                $detailModel->save();

                ExcelExtendService::toHospitalRecord($detailModel->project_id, RevisitingRecord::TYPE_CONSUME, $detailModel->event_at, $detailModel->patient_card_id, self::getSection($value['section'], $hospital, 'clinic_id'), $detailModel->id);

                $transaction->commit();
            } catch (Exception $e) {
                $transaction->rollBack();

                throw new HttpException(500, $e->getMessage());
            }
        }
    }

    /**
     * 统计全部
     * @param $data
     * @param $hospital
     */
    public static function all_updateConsumption($data, $hospital)
    {
        // 第一步优化 查询detail
        $project_id = self::getProject($hospital);

        // 详情表已经统计出来的id
        $yiyuanIds = ConsumptionDetail::find()
            ->select('yiyuan_aid')
            ->where(['project_id' => $project_id])
            ->column();

        // 统计治疗项目合计
        $allConsumption = Consumption::find()
            ->select('id, patient_card_id, clinic_time')
            ->where(['project_id' => $project_id])
            ->asArray()
            ->all();

        $allConsumptionArray = [];
        foreach ($allConsumption as $value) {
            $allConsumptionArray[$value['patient_card_id']][$value['clinic_time']] = $value['id'];
        }

        $dataArray = [];
        foreach ($data as $value) {
            //查询这条记录有没有记录过
            if (in_array($value['id'], $yiyuanIds)) {
                continue;
            }
            $clinic_time = strtotime($value['event_time']);
            $dataArray[$value['card_id']][$clinic_time][] = $value;
        }
        unset($data);

        // 判断数据有没有同步到
        foreach ($dataArray as $patient_card_id => $clinic_timeArray) {

            foreach ($clinic_timeArray as $clinic_time => $value) {

                $insertDetail = [];

                // 判断有没有合计过
                $all_id = $allConsumptionArray[$patient_card_id][$clinic_time] ?? 0;
                if ($all_id) {
                    // 暂时不可能,同一个时间段,分开导入现象

                } else {

                    $transaction = Yii::$app->db->beginTransaction();
                    try {
                        // 没有合计数据
                        $discounted_moneyArray = array_column($value, 'discounted_money');
                        $model = new Consumption();
                        $model->clinic_time = strtotime($value[0]['event_time']);
                        $model->project_id = $project_id;
                        $model->patient_card_id = $value[0]['card_id'];
                        $model->clinic_id = self::getSection($value[0]['section'], $hospital, 'clinic_id');
                        $model->consulting_room = self::getSection($value[0]['section'], $hospital, 'clinic_name');
                        $model->doctor_name = $value[0]['doctor_name'];
                        $model->money = 0;
                        $model->refund_money = 0;

                        foreach ($discounted_moneyArray as $discounted_money) {

                            if ($discounted_money > 0) {
                                $model->money += $discounted_money;
                            } elseif ($discounted_money < 0) {
                                $model->refund_money += $discounted_money;
                            }
                            $model->reality_money += $discounted_money;
                        }

                        $model->trade_type = $model->reality_money > 0 ? Consumption::TRADE_TYPE_BOOKED : Consumption::TRADE_TYPE_REFUND;
                        $model->save();

                        foreach ($value as $detail) {
                            $insertDetail[] = [
                                'yiyuan_aid' => $detail['id'],
                                'consumption_id' => $model->id,
                                'patient_card_id' => $detail['card_id'],
                                'drug_name' => $detail['drug'],
                                'drug_num' => $detail['count'],
                                'drug_unit' => $detail['unit'],
                                'drug_type' => $detail['money_name'],
                                'price' => $detail['price'],
                                'money' => $detail['sales_money'],
                                'reality_money' => $detail['discounted_money'],
                                'consumption_type' => $detail['discounted_money'] > 0 ? ConsumptionDetail::CONSUMPTION_TYPE_BOOKED : ConsumptionDetail::CONSUMPTION_TYPE_REFUND,
                                'event_at' => strtotime($detail['event_time']),
                                'discount_rate' => $detail['sales_money'] != 0 ? $detail['discounted_money'] / $detail['sales_money'] : 0,
                                'project_id' => $project_id
                            ];
                        }

                        $detailItem = [
                            'yiyuan_aid', 'consumption_id', 'patient_card_id', 'drug_name', 'drug_num',
                            'drug_unit', 'drug_type', 'price', 'money', 'reality_money', 'consumption_type',
                            'event_at', 'discount_rate', 'project_id'
                        ];

                        Yii::$app->db->createCommand()->batchInsert(ConsumptionDetail::tableName(), $detailItem, $insertDetail)->execute();

                        $transaction->commit();
                    } catch (Exception $e) {
                        $transaction->rollBack();
                    }
                }
            }
        }
    }

    /**
     * 更新,白友patient_user,patient_clinic_record,
     */
    public static function recordDeal($data, $hospital)
    {
        $tempArray = [];
        // 数据处理 按照  card_id/日期 处理数组
        foreach ($data as $value) {
            $day = date('Y-m-d', strtotime($value['event_time']));
            $tempArray[$value['card_id']][$day] = $value;
        }

        foreach ($tempArray as $card_id => $dayArray) {

            foreach ($dayArray as $day => $value) {

                $transaction = Yii::$app->db->beginTransaction();
                try {
                    self::updateRecode($card_id, $value['event_time'], $hospital);
                    $transaction->commit();
                } catch (\Exception $exception) {
                    $params = [
                        'hospital' => $hospital,
                        'function' => 'updateRecode',
                        'day' => date('Y-m-d H:i:s'),
                        'content' => $exception->getMessage(),
                        'status' => -1,
                    ];
                    ExcelService::errorLog($params);
                    $transaction->rollBack();
                }

            }

        }

        return true;
    }

    /**
     * 更新,白友patient_user,patient_clinic_record,
     */
    public static function all_recordDeal($data, $hospital)
    {
        $tempArray = [];
        // 数据处理 按照  card_id/日期 处理数组
        foreach ($data as $value) {
            $day = date('Y-m-d', strtotime($value['event_time']));
            $tempArray[$value['card_id']][$day] = $value;
        }

        $project_id = self::getProject($hospital);

        // 获取用户信息
        $patientArray = User::find()
            ->select('patient_card_id,id,last_revisiting_time,reg_time,revisiting_count')
            ->andWhere(['project_id' => $project_id])
            ->asArray()
            ->all();

        $patientArray = array_column($patientArray, null, 'patient_card_id');

        // 查询挂号信息
        $recordArray = ClinicRecord::find()
            ->select('patient_user_id, group_concat(clinic_day) as day_array')
            ->where(['project_id' => self::getProject($hospital)])
            ->groupBy('patient_user_id')
            ->asArray()
            ->all();

        foreach ($recordArray as &$value) {
            $value['day_array'] = explode(',', $value['day_array']);
        }

        $insertRecord = [];
        $updateArray = [];
        //记录需要更新的 patientId
        $updatePatientIds = [];

        foreach ($tempArray as $card_id => $dayArray) {

            foreach ($dayArray as $day => $value) {

                $firstDay = date('Y-m-01', strtotime($day));
                $lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));
                // 月初时间
                $startTime = $firstDay . " 00:00:00";
                // 月末时间
                $endTime = $lastDay . " 23:59:59";

                // 判断用户是否存在
                $patientId = $patientArray[$value['card_id']]['id'] ?? 0;

                if (!$patientId) {
                    // 用户不存在,跳过
                    continue;
                }

                $recordDay = $recordArray[$patientId] ?? [];

                // 查询到诊记录
                if (in_array($day, $recordDay)) {
                    continue;
                } else {

                    // 判断是不是初诊
                    $reg_time = $patientArray[$value['card_id']]['reg_time'];

                    $is_initial_clinic = ClinicRecord::CLINIC_SECOND;
                    if (strtotime($startTime) > $reg_time && strtotime($endTime) < $reg_time) {
                        $is_initial_clinic = ClinicRecord::CLINIC_FIRST;
                    }

                    // 插入到诊记录
                    $insertRecord[] = [
                        'project_id' => $project_id,
                        'patient_user_id' => $patientId,
                        'clinic_time' => strtotime($value['event_time']),
                        'source' => ClinicRecord::SOURCE_HOSPITAL,
                        'clinic_day' => $day,
                        'is_initial_clinic' => $is_initial_clinic
                    ];

                    // 更新patient_user 表到诊次数
                    $last_revisiting_time = $patientArray[$value['card_id']]['last_revisiting_time'];
                    $patientArray[$value['card_id']]['last_revisiting_time'] = $last_revisiting_time > strtotime($value['event_time']) ? $last_revisiting_time : strtotime($value['event_time']);
                    $patientArray[$value['card_id']]['revisiting_count']++;
                    $updatePatientIds[] = $value['card_id'];
                }
            }
        }

        $updatePatientIds = array_unique($updatePatientIds);

        $transaction = Yii::$app->db->beginTransaction();
        try {

            foreach ($updatePatientIds as $card_id) {
                $userModel = User::findOne($patientArray[$card_id]['id']);
                $userModel->last_revisiting_time = $patientArray[$card_id]['last_revisiting_time'];
                $userModel->revisiting_count = $patientArray[$card_id]['revisiting_count'];
                $userModel->save();
            }

            $insertItem = [
                'project_id',
                'patient_user_id',
                'clinic_time',
                'source',
                'clinic_day',
                'is_initial_clinic'
            ];
            Yii::$app->db->createCommand()->batchInsert(ClinicRecord::tableName(), $insertItem, $insertRecord)->execute();

            $transaction->commit();

        } catch (\Exception $exception) {

            $params = [
                'hospital' => $hospital,
                'function' => 'all_recordDeal',
                'day' => date('Y-m-d H:i:s'),
                'content' => $exception->getMessage(),
                'status' => -1,
            ];
            ExcelService::errorLog($params);
            $transaction->rollBack();
        }


        return true;
    }

    /**
     * 更新by_clinic_user_treatment_detail,by_clinic_user_treatment_project表
     *
     * @param $data
     * @param $hospital
     * @return bool
     */
    public static function all_updateTreatment($data, $hospital)
    {

        $project_id = self::getProject($hospital);

        // 详情表已经统计出来的id
        $yiyuanIds = UserTreatmentDetail::find()
            ->select('yiyuan_aid')
            ->where(['project_id' => $project_id])
            ->column();

        // 统计治疗项目合计
        $allTreatment = UserTreatmentProject::find()
            ->select('id, patient_card_id, clinic_project_id')
            ->where(['project_id' => $project_id])
            ->asArray()
            ->all();

        // 治疗项目合计分类
        $treatmentArray = [];
        foreach ($allTreatment as $value) {
            $treatmentArray[$value['patient_card_id']][$value['clinic_project_id']] = $value['id'];
        }

        $insertData = [];
        $insertProjectTemp = [];
        $updateProjectTemp = [];

        $time = time();

        foreach ($data as $value) {

            //查询这条记录有没有记录过
            if (in_array($value['id'], $yiyuanIds)) {
                continue;
            }

            $value['drug'] = self::drugName($value['drug'], $hospital);
            $drug = $value['drug'];
            // 判断这条药品数据是不是,白友需要的数据
            $clinic_project_id = self::getClinicProject($hospital, $drug);

            if (!$clinic_project_id) {
                continue;
            }

            // 插入详情的数据
            $insertData[] = [
                'patient_card_id' => $value['card_id'],
                'project_id' => $project_id,
                'yiyuan_aid' => $value['id'],
                'name' => $value['patient_name'],
                'doctor_name' => $value['doctor_name'],
                'section_name' => self::getSection($value['section'], $hospital, 'clinic_name'),
                'clinic_project_id' => $clinic_project_id,
                'clinic_project_name' => $drug,
                'num' => $value['count'],
                'user_name' => $value['user_name'],
                'event_time' => $value['event_time'],
                'created_at' => $time,
                'updated_at' => $time
            ];

            // 查询是更新项目详情还是插入

            $detailId = $treatmentArray[$value['card_id']][$clinic_project_id] ?? 0;

            if ($detailId) {
                $tempDetail = $updateProjectTemp[$value['card_id']][$clinic_project_id] ?? [];
                $num = $tempDetail['num'] ?? 0;
                $num += $value['count'];
                $updateProjectTemp[$value['card_id']][$clinic_project_id] = [
                    'id' => $detailId,
                    'num' => $num,
                ];
            } else {
                $tempDetail = $insertProjectTemp[$value['card_id']][$clinic_project_id] ?? [];
                $total_num = $tempDetail['total_num'] ?? 0;
                $total_num += $value['count'];
                $insertProjectTemp[$value['card_id']][$clinic_project_id] = [
                    'total_num' => $total_num,
                    'clinic_project_name' => $drug,
                    'name' => $value['patient_name']
                ];

            }
        }

        $is_up = 0;
        $insertProject = [];
        foreach ($insertProjectTemp as $patient_card_id => $value) {

            foreach ($value as $clinic_project_id => $detail) {

                $insertProject[] = [
                    'project_id' => $project_id,
                    'patient_card_id' => $patient_card_id,
                    'name' => $detail['name'],
                    'clinic_project_id' => $clinic_project_id,
                    'clinic_project_name' => $detail['clinic_project_name'],
                    'total_num' => $detail['total_num'],
                    'created_at' => $time,
                    'updated_at' => $time,
                ];
            }
        }

        $sql_up = 'update ' . UserTreatmentProject::tableName() . ' set total_num = ( case ';
        $ids = [];
        foreach ($updateProjectTemp as $pid => $value) {

            foreach ($value as $clinic_project_id => $detail) {
                $is_up = 1;

                $sql_up .= ' when id = ' . $detail['id'] . ' then total_num + ' . $detail['num'];
                $ids[] = $detail['id'];
            }
        }

        $sql_up .= " end ) where id in ( " . implode(',', $ids) . " )";


        $transaction = Yii::$app->db->beginTransaction();
        try {

            $projectItem = [
                'project_id', 'patient_card_id', 'name', 'clinic_project_id', 'clinic_project_name', 'total_num', 'created_at', 'updated_at',
            ];
            Yii::$app->db->createCommand()->batchInsert(UserTreatmentProject::tableName(), $projectItem, $insertProject)->execute();

            $detailItem = [
                'patient_card_id', 'project_id', 'yiyuan_aid', 'name', 'doctor_name', 'section_name', 'clinic_project_id', 'clinic_project_name',
                'num', 'user_name', 'event_time', 'created_at', 'updated_at'
            ];

            Yii::$app->db->createCommand()->batchInsert(UserTreatmentDetail::tableName(), $detailItem, $insertData)->execute();
            if ($is_up == 1) {
                Yii::$app->db->createCommand($sql_up)->queryAll();
            }

            $transaction->commit();
        } catch (\Exception $exception) {

            $params = [
                'hospital' => $hospital,
                'function' => 'all_updateTreatment',
                'day' => date('Y-m-d H:i:s'),
                'content' => $exception->getMessage(),
                'status' => -1,
            ];
            ExcelService::errorLog($params);
            $transaction->rollBack();
        }


        return true;
    }

    /**
     * 更新by_clinic_user_treatment_detail,by_clinic_user_treatment_project表
     *
     * @param $data
     * @param $hospital
     * @return bool
     */
    public static function updateTreatment($data, $hospital)
    {
        foreach ($data as $value) {

            $value['drug'] = self::drugName($value['drug'], $hospital);
            // 判断这条药品数据是不是,白友需要的数据
            $clinic_project_id = self::getClinicProject($hospital, trim($value['drug']));


            if (!$clinic_project_id) {
                continue;
            }
            //查询这条记录有没有记录过
            $res = UserTreatmentDetail::find()
                ->where(['yiyuan_aid' => $value['id']])
                ->andWhere(['project_id' => self::getProject($hospital)])
                ->exists();

            if ($res) {
                continue;
            }

            $transaction = Yii::$app->db->beginTransaction();
            try {

                $drug = $value['drug'];
                $detailModel = new UserTreatmentDetail();
                $detailModel->patient_card_id = $value['card_id'];
                $detailModel->project_id = self::getProject($hospital);
                $detailModel->yiyuan_aid = $value['id'];
                $detailModel->name = $value['patient_name'];
                $detailModel->doctor_name = $value['doctor_name'];
                $detailModel->section_name = self::getSection($value['section'], $hospital, 'clinic_name');
                $detailModel->clinic_project_id = $clinic_project_id;
                $detailModel->clinic_project_name = $drug;
                $detailModel->num = $value['count'];
                $detailModel->user_name = $value['user_name'];
                $detailModel->event_time = $value['event_time'];
                $detailModel->save();
                // 录入合计
                $allModel = UserTreatmentProject::find()
                    ->where([
                        'patient_card_id' => $value['card_id'],
                        'clinic_project_id' => $clinic_project_id,
                    ])
                    ->one();

                if (!$allModel) {
                    $allModel = new UserTreatmentProject();
                }
                $allModel->project_id = self::getProject($hospital);
                $allModel->patient_card_id = $value['card_id'];
                $allModel->name = $value['patient_name'];
                $allModel->clinic_project_id = $clinic_project_id;
                $allModel->clinic_project_name = $value['drug'];
                $allModel->total_num += $value['count'];
                $allModel->save();

                $transaction->commit();
            } catch (\Exception $e) {

                $params = [
                    'hospital' => $hospital,
                    'function' => 'updateTreatment',
                    'day' => date('Y-m-d H:i:s'),
                    'content' => $e->getMessage(),
                    'status' => -1,
                ];
                ExcelService::errorLog($params);

                $transaction->rollback();
            }
        }

        return true;
    }

    /**
     * @param $sheetData excel 数据
     * @param $hospital
     * @return array|bool
     */
    public static function registrationDocuments($sheetData, $hospital)
    {
        RegistrationList::$pix = $hospital;
        SectionList::$pix = $hospital;
        $project_id = Project::find()
            ->select('id')
            ->where(['name_sx' => $hospital])
            ->asArray()
            ->one();

        $headArray = RegistrationHeader::find()
            ->where(['hospital' => $hospital])
            ->andWhere(['status' => 1])
            ->asArray()
            ->one();

        //从第三行开始有正式数据
        $array = array_diff_key($sheetData, [1, 2, 3, 4]);
        $sectionInfo = SectionList::find()
            ->asArray()
            ->all();
        $sectionInfo = array_column($sectionInfo, 'id', 'section');
        foreach ($array as $k => $v) {

            if (empty($v[$headArray['card_id']])) {
                continue;
            }

            if (!empty($v[$headArray['card_id']]) && !empty($v[$headArray['truename']])) {

                //判断门诊部门存不存在,如果不存在插入一条新数据重新
                if (!isset($sectionInfo[$v[$headArray['section']]])) {
                    $listModel = new SectionList();
                    $listModel->section = $v[$headArray['section']];
                    $listModel->save();
                    $sectionInfo = SectionList::find()
                        ->asArray()
                        ->all();
                    $sectionInfo = array_column($sectionInfo, 'id', 'section');
                }
                //判断该磁卡号有没有重复 如果有重复覆盖该条数据
                $model = RegistrationList::find()
                    ->where(['card_id' => $v[$headArray['card_id']]])
                    ->one();

                if ($model) {
                    //如果当前单据号是新的则直接跳过

                    if (strtotime($model->registration_time) <= strtotime($v[$headArray['registration_time']])) {
                        continue;
                    }


                } else {
                    $model = new RegistrationList();
                }
                $model->document_id = $v[$headArray['document_id']] ?? 0;
                $model->card_id = $v[$headArray['card_id']];
                $model->truename = $v[$headArray['truename']];
                $model->sex = $v[$headArray['sex']];

                if ($hospital == 'nt') {
                    $age = $v[$headArray['birthday']] ?? 0;
                    $age = str_replace(' ', '', $age);

                    if (strpos($age, '周岁') !== false) {
                        $age = str_replace('周岁', '', $age);
                    } else {
                        $age = 0;
                    }
                    $year = date('Y', strtotime($v[$headArray['registration_time']]));
                    $model->birthday = $year - $age . "-01-01 00:00:00";

                } elseif ($hospital == 'cs') {

                    $age = $v[$headArray['birthday']] ?? 0;
                    $age = str_replace(' ', '', $age);

                    if (strpos($age, '岁') !== false) {
                        $age = str_replace('岁', '', $age);
                    } elseif (strpos($age, '月') !== false) {
                        $age = 0;
                    } elseif (strpos($age, '小时') !== false) {
                        $age = 0;
                    } else {
                        print_r($age);
                        die();
                    }

                    $year = date('Y', strtotime($v[$headArray['registration_time']]));
                    $model->birthday = $year - $age . "-01-01 00:00:00";


                } else {
                    $model->birthday = $v[$headArray['birthday']];
                }
                $model->registration_time = $v[$headArray['registration_time']];
                $model->section = $sectionInfo[$v[$headArray['section']]];
                $model->doctor_name = $v[$headArray['doctor_name']];
                $model->disease_type = $v[$headArray['disease_type']] ?? '';
                $model->registration_type = $v[$headArray['registration_type']];
                $model->message_source = $v[$headArray['message_source']];
                $model->mobile = empty($v[$headArray['mobile']]) ? '' : $v[$headArray['mobile']];
                $model->address = $v[$headArray['address']];
                $model->phone = $v[$headArray['phone']] ?? '';
                $model->salesman = empty($v[$headArray['salesman']] ?? '') ? '' : $v[$headArray['salesman']];
                $model->operator = $v[$headArray['operator']] ?? '';
                $model->Insurance_pay = $v[$headArray['Insurance_pay']] ?? 0;
                $model->person_pay = $v[$headArray['person_pay']] ?? 0;
                $model->registration_fee = $v[$headArray['registration_fee']] ?? 0;
                $model->treatment = $v[$headArray['treatment']] ?? 0;
                $model->other_fee = $v[$headArray['other_fee']] ?? 0;
                $model->Summary_time = empty($v[$headArray['Summary_time']]) ? '0000-00-00 00:00:00' : $v[$headArray['Summary_time']];
                $model->created_time = time();


                if ($model->save()) {
                    // 同步更新,患者到诊时间关联(patient_user)
                    if (!empty($project_id['id'])) {
                        $day = mb_substr($v[$headArray['registration_time']], 0, 10);
                        $start_day = strtotime($day . ' 00:00:00');
                        $end_day = strtotime($day . ' 23:59:59');

                        $mobile = $v[$headArray['mobile']] ?? '';
                        $phone = $v[$headArray['phone']] ?? '';

                        if (empty($mobile) && empty($phone)) {
                            continue;
                        }
                        $is_mobile = !empty($mobile) ? $mobile : $phone;

                        $ret = \common\models\hospital\User::find()
                            ->select('id,consult_room,arrival_visit_time')
                            ->where(['and',
                                    ['project_id' => $project_id['id']],
                                    ['<', 'appoint_time', $end_day],
                                    ['>', 'appoint_time', $start_day],
                                    ['like', 'mobile', $is_mobile],
                                    ['consult_room' => ''],
                                ]
                            )->all();

                        foreach ($ret as $model) {
                            $model->consult_room = $v[$headArray['section']];
                            $model->arrival_visit_time = strtotime($v[$headArray['registration_time']]);
                            $model->save(); // skipping validation as no user input is involved
                        }
                    }
                } else {
                    $params = [
                        'hospital' => $hospital,
                        'function' => 'registrationDocuments',
                        'day' => date('Y-m-d H:i:s'),
                        'content' => $model->errors,
                        'status' => -1,
                    ];
                    ExcelService::errorLog($params);
                    print_r($model->errors);
                    die();
                    return false;
                }
            }
        }

        return true;
    }


    /**
     * @apiName
     * @param $allData
     * @param $hospital
     * @author loujie
     */
//    public static function updateExpenseRecord($allData,$hospital)
//    {
//        $data = [];
//        foreach ($allData as $item) {
//            $data[$item['card_id']][$item['event_time']] = 1;
//        }
//
//        $project_id = self::getProject($hospital);
//
//        foreach ($data as $patient_card_id => $timeArray) {
//
//            foreach ($timeArray as $time => $value) {
//
//                ExcelExtendService::toHospitalRecord($project_id, RevisitingRecord::TYPE_CONSUME, strtotime($time), $patient_card_id,  $clinic_id, $source_id);
//            }
//        }
//
//    }


    /**
     * (方法废弃: 之前的需求,根据消费信息,判断来源次数,初诊复诊)
     * 更新白友 到诊记录和
     *
     * @param $card_id 磁卡号
     * @param $clinic_time 到诊时间
     * @param $hospital 医院名称
     * @return bool
     */
    public static function updateRecode($card_id, $clinic_time, $hospital)
    {
        // 查询有没有这个患者
        $patientModel = User::find()
            ->select('id,revisiting_count,last_revisiting_time')
            ->where(['patient_card_id' => $card_id])
            ->andWhere(['project_id' => self::getProject($hospital), 'status' => User::STATUS_ENABLE])
            ->one();

        if (!$patientModel) {
            $patientModel = new User();
            $patientModel->patient_card_id = (string)$card_id;
            $patientModel->project_id = self::getProject($hospital);
            $patientModel->save();
        }
        // 判断是初诊还是复诊  true是初诊
        $day = mb_substr($clinic_time, 0, 10);
        $firstDay = date('Y-m-01', strtotime($clinic_time));
        $lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));
        $startTime = $firstDay . " 00:00:00";
        $endTime = $lastDay . " 23:59:59";
        RegistrationList::$pix = $hospital;
        $result = RegistrationList::find()
            ->select('id')
            ->where(['card_id' => $card_id])
            ->andWhere(['and', ['>', 'registration_time', $startTime], ['<', 'registration_time', $endTime]])
            ->exists();
        $is_record = 0;
        // 查询患者记录表 有就更新,没有就插入
        $clinicModel = ClinicRecord::find()
            ->where(['clinic_day' => $day, 'patient_user_id' => $patientModel->id])
            ->andWhere(['project_id' => self::getProject($hospital)])
            ->one();

        if (!$clinicModel) {
            $is_record = 1;
            $clinicModel = new ClinicRecord();
            $clinicModel->project_id = self::getProject($hospital);
            $clinicModel->patient_user_id = $patientModel->id;
            $clinicModel->clinic_time = strtotime($clinic_time);
            $clinicModel->source = ClinicRecord::SOURCE_HOSPITAL;
            $clinicModel->created_at = time();
            $clinicModel->clinic_day = $day;
        }
        $clinicModel->is_initial_clinic = $result ? ClinicRecord::CLINIC_FIRST : ClinicRecord::CLINIC_SECOND;
        $clinicModel->updated_at = time();

        if (!$clinicModel->save()) {
            print_r($clinicModel->errors);
            die();
        }

        // 更新 patient_user 来院次数和 上次到诊时间
        if ($is_record == 1) {
            //$patientModel->revisiting_count += 1;

            // 如果消费时间 大于上次到诊时间,更新上次到诊时间
//            if (strtotime($clinic_time) > $patientModel->last_revisiting_time) {
//                $patientModel->last_revisiting_time = strtotime($clinic_time);
//                // 上次到诊时间> 下次复诊时间,清空下次复诊时间
//                $patientModel->last_revisiting_time > $patientModel->next_revisiting_time ? $patientModel->next_revisiting_time = 0 : '';
//                $patientModel->missed_days = self::getMissedDays($clinic_time);
//            }
            // 更新未到诊天数

            if (!$patientModel->save()) {
                print_r($patientModel->errors);
                die();
            }
        }
        return true;
    }


    /**
     * 根据项目简称获取项目id
     *
     * @param $name_sx
     * @return mixed
     */
    public static function getProject($name_sx)
    {
        if (empty(self::$projectArray)) {
            $array = Project::find()
                ->select('id,name_sx')
                ->asArray()
                ->all();
            self::$projectArray = array_column($array, null, 'name_sx');
        }

        return self::$projectArray[$name_sx]['id'];
    }

    /**
     * 根据项目简称获取项目id
     *
     * @param $section
     * @param $hospital
     * @param string $item  item = clinic_id  对应白友诊室id  item = clinic_name
     * @return mixed
     */
    public static function getSection($section, $hospital, $item)
    {
        SectionList::$pix = $hospital;
        if (empty(self::$sectionArray)) {
            $array = SectionList::find()
                ->asArray()
                ->all();
            self::$sectionArray = array_column($array, null, 'id');
        }

//        // 诊室名统一
//        $clinic_name = self::$sectionArray[$section]['section'];
//        $clinic_name = SectionList::$sectionName[$hospital][$clinic_name] ?? $clinic_name;
        return self::$sectionArray[$section][$item];
    }

    /**
     * 获取白友全局设置
     * @param string $type 获取全局设置类型 默认查询初诊下次回访时间N天后
     * @param $hospital
     * @return mixed
     */
    public static function getConfig($type, $hospital)
    {
        if (empty(self::$configArray)) {
            $array = Config::find()
                ->where(['project_id' => self::getProject($hospital)])
                ->asArray()
                ->all();
            self::$configArray = array_column($array, null, 'config_name');
        }

        return self::$configArray[$type]['config_value'] ?? '';
    }

    /**
     * 根据奕远项目名,获取白友诊疗项目id
     *
     * @param $hospital
     * @param $yiyuan_name
     * @return mixed
     */
    public static function getClinicProject($hospital, $yiyuan_name)
    {
        // 所有中文输入法全换成中文输入法
        if (empty(self::$clinicProjectArray)) {
            $array = clinic_project::find()
                ->select('id,bind_yiyuan_name')
                ->where(['project_id' => self::getProject($hospital)])
                ->asArray()
                ->all();

            foreach ($array as &$value) {
                $value['bind_yiyuan_name'] = self::toreplace($value['bind_yiyuan_name'], '(');
            }
            self::$clinicProjectArray = array_column($array, null, 'bind_yiyuan_name');
        }

        return self::$clinicProjectArray[$yiyuan_name]['id'] ?? 0;
    }

    /**
     * 计算实际到诊天数
     * @param $event_time
     * @return float
     */
    public static function getMissedDays($event_time)
    {
        $Date_2 = date("Y-m-d");
        $Date_1 = date('Y-m-d', $event_time);
        $d1 = strtotime($Date_1);
        $d2 = strtotime($Date_2);
        $Days = round(($d2 - $d1) / 3600 / 24);

        return $Days;

    }

    // 去掉括号 截取括号前面的内容
    public static function toreplace($str, $find)//$str是你需要操作的字符串,$find是你指定的字符串
    {
        // 中文符合转变成 英文符号
        $str = str_replace(' ', '', $str);
        $str = str_replace('，', ',', $str);
        $str = str_replace('（', '(', $str);
        $str = str_replace('）', ')', $str);
        $str = str_replace('－', '-', $str);

        if (strpos($str, $find) === false) {
            return $str;
        }
        $a = explode($find, $str);
        return $a[0];
    }

    // 处理温州  - 等特殊符号
    public static function wzDealDrug($str, $hospital)
    {
        //根据 '-' 截断
        $array = explode('-', $str);
        $drugArray = Expense::$drugProject[$hospital] ?? [];

        foreach ($array as $value) {

            if (in_array($value, $drugArray)) {
                return $value;
            }

        }
        return $str;
    }

    /**
     * 字符串最后一个是数字去掉
     * @param $str
     * @param $hospital
     * @return false|string
     */
    public static function numDealDrug($str, $hospital)
    {

        //如果,字符串最后一个是数字,则去掉
        if (is_numeric(substr($str, -1))) {
            return substr($str, 0, strlen($str) - 1);
        }

        return $str;


    }

    /**
     * 药品项目名转换
     * @param $str
     * @param $hospital
     * @return mixed
     */
    public static function drugName($str, $hospital)
    {
        $str = self::toreplace($str, '*');
        if ($hospital == 'cs') {
            $str = Expense::$drugSpecial[$hospital][$str] ?? $str;
        }

        $str = self::toreplace($str, '(');
        //如果是温州的,要修改 处理 -
        if ($hospital == 'wz' || $hospital == 'sz' || $hospital == 'nt') {
            $str = self::wzDealDrug($str, $hospital);
        }

        if ($hospital == 'gz') {
            $str = Expense::$drugSpecial[$hospital][$str] ?? $str;
        }

        if ($hospital == 'nb') {
            $str = self::numDealDrug($str, $hospital);
            $str = Expense::$drugSpecial[$hospital][$str] ?? $str;
        }

        return $str;
    }

    /**
     *  获取,对应科室的医助
     * @param $hospital
     * @param $clinic_id
     * @return mixed
     */
    public static function getClinicRoom($hospital, $clinic_id)
    {

        if (empty(self::$clinicRoomArray[$hospital])) {
            $array = Clinic::find()
                ->alias('c')
                ->select(['c.id', 'c.name', 'count(a.member_id) as count', 'group_concat(a.member_id) as member'])
                ->leftJoin(Attr::tableName() . ' a', ' a.clinic_id = c.id')
                ->leftJoin(Member::tableName() . ' m', ' m.id = a.member_id')
                ->where(['c.project_id' => self::getProject($hospital)])
                ->andWhere(['c.status' => Clinic::STATUS_ENABLE])
                ->andWhere(['m.status' => Member::STATUS_ENABLE])
                ->andWhere(['a.profession_id' => Profession::ID_MEDICAL])
                ->groupBy('a.clinic_id')
                ->asArray()
                ->all();

            $clinicList = Clinic::find()
                ->alias('c')
                ->select('c.id,c.name')
                ->where(['c.project_id' => self::getProject($hospital)])
                ->andWhere(['c.status' => Clinic::STATUS_ENABLE])
                ->asArray()
                ->all();

            foreach ($array as &$value) {
                $value['member'] = $value['member'] ? explode(',', $value['member']) : [];
            }

            self::$clinicRoomArray[$hospital] = array_column($array, null, 'id');

            $clinicIds = array_column($array, 'id');

            foreach ($clinicList as $value) {

                if (in_array($value['id'], $clinicIds)) {
                    continue;
                }

                self::$clinicRoomArray[$hospital][$value['id']] = self::$clinicRoomArray[$value['id']] ?? [
                        'id' => $value['id'],
                        'name' => $value['name'],
                        'count' => 0,
                    ];
            }
        }

        return self::$clinicRoomArray[$hospital][$clinic_id] ?? [];
    }

    /**
     * 获取,对应科室的客服
     *
     * @param $hospital
     * @param $clinic_id
     * @return mixed
     */
    public static function getCustomerService($hospital, $clinic_id)
    {
        if (empty(self::$customerServiceArray)) {
            $array = Clinic::find()
                ->alias('c')
                ->select(['c.id', 'c.name', 'count(a.kefu_id) as count', 'group_concat(m.realname) as realname', 'group_concat(a.kefu_id) as member'])
                ->leftJoin(RelationKefu::tableName() . ' a', ' a.clinic_id = c.id')
                ->leftJoin(Member::tableName() . ' m', ' m.id = a.kefu_id')
                ->leftJoin(Attr::tableName() . ' attr', 'attr.member_id = a.kefu_id and attr.project_id = ' . self::getProject($hospital))
                ->where(['c.project_id' => self::getProject($hospital)])
                ->andWhere(['c.status' => Clinic::STATUS_ENABLE])
                ->andWhere(['m.status' => Member::STATUS_ENABLE])
                ->andWhere(['attr.profession_id' => [Profession::ID_CUSTOMER, Profession::ID_CUSTOMER_LEADER]])
                ->groupBy('a.clinic_id')
                ->asArray()
                ->all();

            foreach ($array as &$value) {
                $value['realname'] = $value['realname'] ? explode(',', $value['realname']) : [];
                $value['member'] = $value['member'] ? explode(',', $value['member']) : [];
            }

            self::$customerServiceArray = array_column($array, null, 'id');
        }

        return self::$customerServiceArray[$clinic_id] ?? [];
    }

    /**
     * 获取就诊类型对应id 初诊,复诊,咨询号等
     *
     * @param $hospital
     * @param $type
     * @return int
     */
    public static function getOutpatientType($hospital, $type)
    {
        if (empty(self::$outpatientTypeArray)) {
//            $array = OutpatientType::find()
//                ->select('id,outpatient_name as name')
//                ->where(['project_id' => self::getProject($hospital),'status' => OutpatientType::STATUS_ENABLE])
//                ->asArray()
//                ->all();

            $array = ManagementReportService::OUTPATIENT_TYPE;

            self::$outpatientTypeArray = $array;
        }

        return self::$outpatientTypeArray[$type] ?? 0;
    }

    public static function getChannel($hospital, $type)
    {
        if (empty(self::$channelArray)) {
            $array = SourceChannel::find()
                ->select('id , source_name as name')
                ->where(['project_id' => self::getProject($hospital)])
                ->asArray()
                ->all();

            self::$channelArray = array_column($array, null, 'name');

        }

        $channelId = self::$channelArray[$type]['id'] ?? 0;
        if (!$channelId) {
            $model = new SourceChannel();
            $model->source_name = $type;
            $model->project_id = self::getProject($hospital);
            $model->save();

            if (!$model->save()) {
                $params = [
                    'hospital' => $hospital,
                    'function' => 'getChannel',
                    'content' => $model->errors,
                    'day' => date('Y-m-d H:i:s'),
                    'status' => -1,
                ];
                ExcelService::errorLog($params);
                print_r($model->errors);
                die();
            }

            $array = SourceChannel::find()
                ->select('id , source_name as name')
                ->where(['project_id' => self::getProject($hospital)])
                ->asArray()
                ->all();

            self::$channelArray = array_column($array, null, 'name');
            $channelId = self::$channelArray[$type]['id'] ?? 0;
        }

        return $channelId;

    }

    /**
     * 白友添加用户信息【中转库患者同步到白友患者】
     * @param string $hospital 医院缩写【hfx、hfy】
     * @param null $day
     * @return bool
     * @throws Exception
     */
    public static function registration($hospital, $day = null, $endDay = null)
    {
        RegistrationList::$pix = $hospital;
        SectionList::$pix = $hospital;
        Expense::$pix = $hospital;

        $consultStr = self::getConfig('global_card_consult', $hospital);
        $pattern = '/^' . str_replace(',', '|^', $consultStr) . '/i';
        $query = RegistrationList::find()
            ->select('card_id,truename as name,section, registration_time,sex,birthday,disease_type,address,phone,mobile,message_source,state,serial_no,city, registration_fee');

        // 如果有天的,更新当天的用户信息
        $start = $end = '';
	    if ($day) {
		    if ($day == 1) {
			    $start = $end = date('Y-m-d');
		    } else {
                $start = $end = $day;
                if ($endDay) {
                    $end = $endDay;
                }
            }
            $query->andWhere([
                'or',
                ['between', 'registration_time', $start.' 00:00:00', $end.' 23:59:59'],
                ['between', 'created_time', strtotime($start), strtotime($end.' 23:59:59')],
            ]);
	    }
        $data = $query->asArray()->all();

        $is_repeat = false;
        // 当天数据有效挂号查重
        if ($day && date('H:i') >= "16:55" && date('H:i') <= "17:05") {
            $is_repeat = true;
        }
        $repeatArray = [];
        // 项目ID
        $projectId = self::getProject($hospital);
        // 查询有效用户的信息
        $cardArrayQuery = User::find()
            ->select('patient_card_id,serial_no,id')
            ->where(['project_id' => $projectId, 'status' => User::STATUS_ENABLE])
            ->andWhere(['!=', 'reg_time', '0']);
        if ($day) {
            $cardArrayQuery->andWhere(['between', 'reg_time', $start . ' 00:00:00', $end . ' 23:59:59']);
        }
        $cardArray = $cardArrayQuery->asArray()->all();

        $cardArray = array_column($cardArray, null, 'patient_card_id');
        foreach ($data as $value) {
            // 指定时间内验证卡号是否重复(只处理有效卡号)
            if ($is_repeat && $value['state'] == 200) {
                if (isset($repeatArray[$value['card_id']])) {
                    $repeatValue = $repeatArray[$value['card_id']];
                    $message = '项目：' . Yii::$app->params[$hospital] . PHP_EOL .
                        '患者A：' . $repeatValue['name'] . '/' . $repeatValue['card_id'] . " 与 患者B：" . $value['name'] . "/" . $repeatValue['card_id'] . '诊疗号重复' . PHP_EOL .
                        '-----------------------------' . PHP_EOL .
                        '请' . Yii::$app->params[$hospital] . '负责人尽快修改患者B诊疗号。' . PHP_EOL . '如需修改患者A诊疗号，修改完成后请尽快联系技术人员修复白友数据';
                    self::sendMessage($message, Yii::$app->params['DING_TOKEN_REPEAT'], Yii::$app->params['DING_KEY_REPEAT'],$hospital);
                } else {
                    $repeatArray[$value['card_id']] = $value;
                }
            }

            // 查到有之前
            if (isset($cardArray[$value['card_id']])) {
                //判断 白友 serial_no是不是0 是0跳过
                if ($cardArray[$value['card_id']]['serial_no'] == 0) {
                    continue;
                }

                //卡号相同 serial_no相同  state不是200 要禁用
                if ($value['state'] != 200 && $cardArray[$value['card_id']]['serial_no'] == $value['serial_no']) {
                    $repeatUser = User::findOne($cardArray[$value['card_id']]['id']);
                    $repeatUser->status = User::STATUS_DELETE;
                    $repeatUser->save();
                    PatientOperateLogService::create($repeatUser->project_id, $repeatUser->id, OperateLog::ACTION_TYPE_HOSPITAL_PATIENT_DELETE, '亦远同步删除患者', 1);
                }
            }
            // 1.退号的卡号不插入
            if ($value['serial_no'] > 0 && $value['state'] != 200) {
                continue;
            }
            // 白友诊室ID
            $clinicId = self::getSection($value['section'], $hospital, 'clinic_id');
            if (empty($clinicId)) {
                continue;
            }
            // 患者信息
            $patient = User::findOne([
                'project_id' => $projectId,
                'patient_card_id' => $value['card_id'],
                'status' => User::STATUS_ENABLE,
            ]);
            if ($patient && $patient->reg_time > 0) {
                continue;
            }
            $oldPatient = new User();// 原患者数据
            // 1.新增or更新患者信息
            if (empty($patient)) {
                $patient = new User();
                $patient->project_id = $projectId;
                $patient->patient_card_id = $value['card_id'];
                $patient->last_revisiting_time = strtotime($value['registration_time']);
                $patient->status = User::STATUS_ENABLE;
            } else {
                $oldPatient->setAttributes($patient->getAttributes());
            }
            $patient->mobile = $hospital == 'hfx' ? ($value['mobile'] ?? '') : ($value['phone'] ?? '');
            $patient->name = $value['name'];
            $patient->birthday = $value['birthday'] ?? '0000-00-00';
            $patient->age = $value['birthday'] ? (date('Y') - date('Y', strtotime($value['birthday']))) : 0;
            $patient->reg_time = strtotime($value['registration_time']);
            $patient->serial_no = $value['serial_no'];
            $patient->gender = self::getGender($value['sex']);
            // 新客户添加为初诊,历史客户添加为复诊
            preg_match($pattern, $value['card_id'], $matches);
            $patient->outpatient_type_id = end($matches)
                ? OutpatientType::ID_ADVISORY
                : (strtotime($value['registration_time']) > strtotime(date("Y-m-01"))
                    ? OutpatientType::ID_FIRST_VISIT
                    : OutpatientType::ID_CONTINUE_VISIT
                );
            $allocationArray = [];// 医助分配记录
            // 查询诊室id
            $assistantArray = self::getClinicRoom($hospital, $clinicId);
            // 新客户分配医助
            if ($assistantArray) {
                $patient->clinic_id = $assistantArray['id'];
                $oldBelongAssistantId = $patient->belong_assistant_id;
                $patient->belong_assistant_id = isset($assistantArray['member']) ? $assistantArray['member'][array_rand($assistantArray['member'])] : 0;
                // 医助分配记录
                if ($patient->belong_assistant_id && $patient->belong_assistant_id != $oldBelongAssistantId) {
                    $allocationArray = [
                        'project_id' => $patient->project_id,
                        'patient_card_id' => $patient->patient_card_id,
                        'member_id' => $patient->belong_assistant_id,
                        'current_profession_id' => AllocationRecord::CURRENT_PROFESSION_ID_MEDICAL
                    ];
                }
            }
            // 来源类型
            $patient->source_channel_id = $value['message_source'] ? self::getChannel($hospital, $value['message_source']) : 0;
            $cityArray = self::dealCity($value['city']);
            if ($cityArray['city_id'] == 0) {
                $cityArray = self::dealCity($value['address']);
            }
            $patient->city_id = $cityArray['city_id'];
            $patient->city_name = $cityArray['city_name'];
            $patient->work_address = $value['city'];
            if (isset($value['address']) && $value['address']) {
                $patient->address = $value['address'];
            }
            // 默认添加上新挂号用户数据的下次回访时间
            $next_day = self::getConfig('global_initial_visit_time', $hospital);
            // 正常情况,挂号时间为当天,异常情况也设置当天加一天
            $next_callback_time = time() + (is_numeric($next_day) ? $next_day : 0) * 60 * 60 * 24;
            if ($next_callback_time > time()) {
                $patient->yz_next_callback_time = $next_callback_time;
            }
            // 完善度
            $patient->degree_num = Yii::$app->services->patientUser->computeDegreeNum([
                'name' => $patient->name,
                'mobile' => $patient->mobile,
                'gender' => $patient->gender,
            ]);
            if (!$patient->save()) {
                // 添加报错记录
                $params = [
                    'hospital' => $hospital,
                    'function' => 'registration',
                    'day' => date('Y-m-d H:i:s'),
                    'content' => $patient->errors,
                    'status' => -1,
                ];
                ExcelService::errorLog($params);
                print_r($patient->errors);
                die();
            }
            // 2.新增or更新记录挂号费
            $registerModel = RegisterFee::find()
                ->where([
                    'serial_no' => $value['serial_no'],
                    'project_id' => $projectId,
                ])
                ->one();
            if (empty($registerModel) && $value['registration_fee'] > 0) {
                $registerModel = new RegisterFee();
                $registerModel->project_id = $projectId;
                $registerModel->serial_no = $value['serial_no'];
            }
            if ($registerModel) {
                $registerModel->patient_card_id = $value['card_id'];
                $registerModel->register_fee = $value['registration_fee'];
                $registerModel->yy_clinic_id = $value['section'];
                $registerModel->yy_clinic_name = self::getSection($value['section'], $hospital, 'section');
                $registerModel->clinic_id = $clinicId;
                $registerModel->registration_time = strtotime($value['registration_time']);
                $registerModel->status = $value['state'] == 200 ? RegisterFee::TYPE_REGISTER : RegisterFee::TYPE_REGISTER_OUT;
                $registerModel->saveAndCheckResult();
            }
            // 3.新增患者就诊类型更新日志
            $insertTemp = [
                'project_id' => $projectId,
                'origin_outpatient_type' => 0,
                'new_outpatient_type' => $patient->outpatient_type_id,
                'remark' => '添加新用户',
                'patient_card_id' => $patient->patient_card_id,
                'created_at' => time(),
                'updated_at' => time(),
            ];
            self::crontabLog([$insertTemp]);
            // 4.添加医助变更记录
            if ($allocationArray) {
                self::allocationRecord($allocationArray);
            }
            // 5-1.患者编辑日志
            PatientOperateLogService::create($patient->project_id, $patient->id, OperateLog::ACTION_TYPE_HOSPITAL_PATIENT_CREATE, PatientOperateLogService::getPatientChangeLog($patient, $oldPatient), 1);
            // 5-2.用户操作日志
            MemberOperateLogService::createHospitalLog('create', $patient, $oldPatient);
        }
        return true;
    }

    /**
     * 获取性别
     */
    public static function getGender($value)
    {
        $genders = array_flip(User::$genders);
        return $genders[$value] ?? User::GENDER_UNKNOWN;
    }

    /**
     *  判断是不是咨询号
     * @param $hospital
     * @return string|string[]|null
     */
    public static function isConsult($hospital, $card_id)
    {
        $consultStr = self::getConfig('global_card_consult', $hospital);
        $pattern = '/^' . str_replace(',', '|^', $consultStr) . '/i';
        preg_match($pattern, $card_id, $matches);

        return $matches ? true : false;
    }

    /**
     * 切换状态,初诊变成复诊 (已被注释)
     * (查询当月挂号及消费信息,满足消费金额为初诊,不满足算流失)
     * @param $hospital
     * @return bool
     * @throws Exception
     */
    public static function firstVisit($hospital)
    {
        $month_start = strtotime(date("Y-m-01"));
        $month_end = strtotime("+1 month -1 seconds", $month_start);

        $firstVisit = self::getOutpatientType($hospital, 'initially');
        $loss = self::getOutpatientType($hospital, 'loss');
        $outpatientArray = [];
        $firstVisit ? $outpatientArray[] = $firstVisit : false;
        $loss ? $outpatientArray[] = $loss : false;
        $patientArray = User::find()
            ->select('id,reg_time,patient_card_id,outpatient_type_id')
            ->where(['and',
                ['project_id' => self::getProject($hospital)],
                ['between', 'reg_time', $month_start, $month_end],
                ['status' => User::STATUS_ENABLE],
                ['outpatient_type_id' => $outpatientArray]
            ])
            ->asArray()
            ->all();

        $lossOrVisit = array_column($patientArray, 'outpatient_type_id', 'patient_card_id');

        // 查询新挂号用户该月消费信息
        $cardArray = array_column($patientArray, 'patient_card_id');
        // 查询白友by_patient_consumption
        $consumptionArray = Consumption::find()
            ->select([
                'sum(reality_money) as money,patient_card_id'
            ])
            ->where(['and',
                ['patient_card_id' => $cardArray],
                ['project_id' => self::getProject($hospital)],
                ['between', 'clinic_time', $month_start, $month_end]
            ])
            ->groupBy('patient_card_id')
            ->asArray()
            ->all();

        //查询流失金额底线
        $leastMoney = self::getConfig('global_loss_amout_money', $hospital);
        $leastMoney = is_numeric($leastMoney) ? $leastMoney : 0;

        // 需要变成流失的用户
        $changeLossData = [];
        // 需要变成初诊的用户
        $changeVisitData = [];

        // 产生消费的用户
        $consumptionPatient = array_column($consumptionArray, 'patient_card_id');
        // 查询挂号,且没有消费信息的用户
        $diffArray = array_diff($cardArray, $consumptionPatient);

        foreach ($diffArray as $value) {
            $temp['patient_card_id'] = $value;
            $temp['money'] = 0;
            $consumptionArray[] = $temp;
        }

        $sqlVisit = "update " . User::tableName() . " set outpatient_type_id = $firstVisit where project_id = " . self::getProject($hospital) . " and patient_card_id in ( ";
        $sqlLoss = "update " . User::tableName() . " set outpatient_type_id = $loss where project_id = " . self::getProject($hospital) . " and patient_card_id in ( ";
        $insertData = [];

        foreach ($consumptionArray as $value) {
            if ($value['money'] > $leastMoney && $lossOrVisit[$value['patient_card_id']] == $loss) {// 当月满足消费,且状态是流失 置为初诊
                $changeVisitData[] = $value['patient_card_id'];
                $sqlVisit .= "'" . $value['patient_card_id'] . "',";
                $insertData[] = [
                    'project_id' => self::getProject($hospital),
                    'origin_outpatient_type' => $loss,
                    'new_outpatient_type' => $firstVisit,
                    'remark' => '当月消费金额' . $value['money'] . '元,最低消费金额' . $leastMoney . '元',
                    'patient_card_id' => $value['patient_card_id'],
                    'created_at' => time(),
                    'updated_at' => time()
                ];

            } elseif ($value['money'] <= $leastMoney && $lossOrVisit[$value['patient_card_id']] == $firstVisit) { // 当月不满足消费,且状态是初诊的 置为流失
                $changeLossData[] = $value['patient_card_id'];
                $sqlLoss .= "'" . $value['patient_card_id'] . "',";
                $insertData[] = [
                    'project_id' => self::getProject($hospital),
                    'origin_outpatient_type' => $firstVisit,
                    'new_outpatient_type' => $loss,
                    'remark' => '当月消费金额' . $value['money'] . '元,最低消费金额' . $leastMoney . '元',
                    'patient_card_id' => $value['patient_card_id'],
                    'created_at' => time(),
                    'updated_at' => time()
                ];
            }

        }

        if (count($changeVisitData) > 0) {
            $sqlVisit = rtrim($sqlVisit, ',');
            $sqlVisit .= ")";
            Yii::$app->db->createCommand($sqlVisit)->execute();
        }

        if (count($changeLossData) > 0) {
            $sqlLoss = rtrim($sqlLoss, ',');
            $sqlLoss .= ")";
            Yii::$app->db->createCommand($sqlLoss)->execute();
        }

        self::crontabLog($insertData);

        return true;
    }

    /**
     *
     * 断诊/流失 -> 复诊
     * 杭州4月14号之前没有消费记录,会影响状态判断,经理确认过,不处理历史数据
     *
     * 本月之前,流失/断诊,在当月有消费记录都算复诊(新: 本月存在到院记录都算复诊)
     * @param $hospital
     * @return bool
     * @throws Exception
     */
    public static function loss($hospital)
    {
        $visit = self::getOutpatientType($hospital, 'referral');
        $loss = self::getOutpatientType($hospital, 'loss');
        $faultDiagnosis = self::getOutpatientType($hospital, 'break');

        // 本月 开始结束时间
        $month_start = strtotime(date("Y-m-01"));
        $month_end = strtotime("+1 month -1 seconds", $month_start);
//
//        // 查询白友by_patient_consumption有消费记录的用户
//        $consumptionIds = Consumption::find()
//            ->select([
//                'patient_card_id'
//            ])
//            ->where(['and',
//                ['between','clinic_time', $month_start, $month_end],
//                ['project_id' => self::getProject($hospital)]
//            ])
//            ->groupBy('patient_card_id')
//            ->column();
//
//        // 查询当月前,所有的流失,断诊,有消费变成复诊
//           $patientArray = User::find()
//            ->select('id,reg_time,patient_card_id,outpatient_type_id')
//            ->where(['and',
//                ['project_id' => self::getProject($hospital)],
//                ['<','reg_time', $month_start],
//                ['status' => User::STATUS_ENABLE],
//                ['outpatient_type_id' => [$loss,$faultDiagnosis,$first] ],
//                ['patient_card_id' => $consumptionIds]
//            ])
//            ->asArray()
//            ->all();

        // 获取天数
        $therapy_time = self::getConfig('global_no_therapy_time', $hospital);
        if (!is_numeric($therapy_time)) {
            return true;
        }

        $begin_time = time() - $therapy_time * 24 * 60 * 60;

        $patientArray = User::find()
            ->select('patient_card_id,outpatient_type_id,id,reg_time,last_revisiting_time,last_clinic_time')
            ->where(['and',
                ['project_id' => self::getProject($hospital)],
                ['>', 'last_revisiting_time', $begin_time],
                ['<', 'reg_time', $month_start],
                ['status' => User::STATUS_ENABLE],
                ['outpatient_type_id' => [$faultDiagnosis, $loss]],
            ])
            ->asArray()
            ->all();

        $patientIds = array_column($patientArray, 'id', 'id');

        if (count($patientIds) == 0) {
            return false;
        }

        $insertData = [];
        foreach ($patientArray as $value) {
            // 查询挂号月  最后到诊月
            $mouthRegTime = date('Y-m', $value['reg_time']);
            $mouthRevisiting = date('Y-m', $value['last_revisiting_time']);
            $mouthClinic = date('Y-m', $value['last_clinic_time']);

            //当月挂号,当月到诊不算复诊 / 治疗时间和挂号时间在一个月
            if ($mouthRegTime == $mouthRevisiting && $mouthRegTime==$mouthClinic) {
                unset($patientIds[$value['id']]);
                continue;
            }

            $temp['project_id'] = self::getProject($hospital);
            $temp['origin_outpatient_type'] = $value['outpatient_type_id'];
            $temp['new_outpatient_type'] = $visit;
            $temp['remark'] = '当月存在来院记录';
            $temp['patient_card_id'] = $value['patient_card_id'];
            $temp['created_at'] = time();
            $temp['updated_at'] = time();
            $insertData[] = $temp;
        }

        $count = User::updateAll(['outpatient_type_id' => $visit, 'updated_at' => time()], ['id' => $patientIds]);
        if ($count > 0) {
            self::crontabLog($insertData);
        }

        return true;
    }


    /**
     * 上个月的初诊->复诊
     * @param $hospital
     * @return bool
     * @throws Exception
     */
    public static function visit($hospital)
    {
        $visit = self::getOutpatientType($hospital, 'referral');
        $firstVisit = self::getOutpatientType($hospital, 'initially');

        // 上月 开始时间结束时间
        $begin_time = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month')));
        $end_time = strtotime(date("Y-m-d 23:59:59", strtotime(-date('d') . 'day')));

        $patientArray = User::find()
            ->select('patient_card_id')
            ->where(['and',
                ['project_id' => self::getProject($hospital)],
                ['between', 'reg_time', $begin_time, $end_time],
                ['status' => User::STATUS_ENABLE],
                ['outpatient_type_id' => $firstVisit]
            ])
            ->column();

        if (count($patientArray) == 0) {
            return false;
        }

        $insertData = [];
        foreach ($patientArray as $value) {
            $insertData[] = [
                'project_id' => self::getProject($hospital),
                'origin_outpatient_type' => $firstVisit,
                'new_outpatient_type' => $visit,
                'remark' => '上月初诊->复诊',
                'patient_card_id' => $value,
                'created_at' => time(),
                'updated_at' => time()
            ];
        }

        $count = User::updateAll(['outpatient_type_id' => $visit], ['patient_card_id' => $patientArray, 'project_id' => self::getProject($hospital)]);
        if ($count > 0) {
            self::crontabLog($insertData);
        }

        return true;

    }


    /**
     * 断诊  抗复发/咨询号,不处理为断诊
     *  添加 流失不变成断诊(流失患者再次到院就诊类型变更为复诊，未再次到院脚本不做就诊类型的变更)
     * 距上次来院时间60天以上未再次来院
     * @param $hospital
     * @return bool
     * @throws Exception
     */
    public static function faultDiagnosis($hospital)
    {
        // 获取天数
        $therapy_time = self::getConfig('global_no_therapy_time', $hospital);
        if (!is_numeric($therapy_time)) {
            return true;
        }

        $begin_time = time() - $therapy_time * 24 * 60 * 60;
        $faultDiagnosis = self::getOutpatientType($hospital, 'break');
        $consulting = self::getOutpatientType($hospital, 'advisory');
        $loss = self::getOutpatientType($hospital, 'loss');

        $patientArray = User::find()
            ->select('patient_card_id,outpatient_type_id')
            ->where(['and',
                ['project_id' => self::getProject($hospital)],
                ['<', 'last_revisiting_time', $begin_time],
//                ['<', 'last_clinic_time', $begin_time],  // 2022.03.04 峰哥说,断诊只根据 上次来院时间判断
                ['status' => User::STATUS_ENABLE],
                ['!=', 'outpatient_type_id', $faultDiagnosis],
                ['!=', 'outpatient_type_id', $consulting],
                ['!=', 'outpatient_type_id', $loss],
                ['is_anti_relapse' => User::IS_ANTI_RELAPSE_NO]
            ])
            ->asArray()
            ->all();

        $insertData = [];
        foreach ($patientArray as $value) {
            $insertData[] = [
                'project_id' => self::getProject($hospital),
                'origin_outpatient_type' => $value['outpatient_type_id'],
                'new_outpatient_type' => $faultDiagnosis,
                'remark' => '超过60天,没有到院',
                'patient_card_id' => $value['patient_card_id'],
                'created_at' => time(),
                'updated_at' => time()
            ];
        }

        $cardIds = array_column($patientArray, 'patient_card_id');
        $count = 0;

        if (count($cardIds) > 0) {
            $count = User::updateAll(['outpatient_type_id' => $faultDiagnosis, "fault_diagnosis_count" => new Expression("fault_diagnosis_count + 1")], ['patient_card_id' => $cardIds, 'project_id' => self::getProject($hospital)]);
        }

        if ($count > 0) {
            self::crontabLog($insertData);
        }

        return true;
    }

    /**
     * 更新就诊状态日志
     * @param $insertData
     * @return void
     * @throws Exception
     */
    public static function crontabLog($insertData): void
    {
        if (empty($insertData)) {
            return;
        }

        Yii::$app->db->createCommand()->batchInsert(
            CrontabLog::tableName(),
            ['project_id', 'origin_outpatient_type', 'new_outpatient_type', 'remark', 'patient_card_id', 'created_at', 'updated_at'],
            $insertData
        )->execute();
    }


    /**
     * 客服选择诊室后，按诊室轮流分配
     * @param $hospital
     * @return void
     */
    public static function distributionCustomer($hospital)
    {
        $outpatientStr = self::getConfig('global_customer_outpatient_type', $hospital);
        if (empty($outpatientStr)) {
            return;
        }

        // 获取符合客服规则的,无客服用户
        $outpatientArray = explode(',', $outpatientStr);
        $project_id = self::getProject($hospital);
        $patientArray = User::find()
            ->select('id,clinic_id,belong_member_id')
            ->where(['project_id' => $project_id])
            ->andWhere(['outpatient_type_id' => $outpatientArray])
            ->andWhere(['belong_member_id' => 0])
            ->andWhere(['>', 'clinic_id', 0])
            ->asArray()
            ->all();

        // 获取客服id
        foreach ($patientArray as $value) {
            $assistantArray = self::getCustomerService($hospital, $value['clinic_id']);

            if ($assistantArray && $assistantArray['count'] > 0) {
                $index = mt_rand(0, $assistantArray['count'] - 1);
                $model = User::findOne($value['id']);
                $model->belong_member_id = $assistantArray['member'][$index];
                $model->belong_member_name = $assistantArray['realname'][$index];

                if ($model->save()) {
                    $allocationArray = [
                        'project_id' => $model->project_id,
                        'patient_card_id' => $model->patient_card_id,
                        'member_id' => $model->belong_member_id,
                        'current_profession_id' => 2
                    ];
                    self::allocationRecord($allocationArray);
                }
            }
        }
    }


    // 修复,上次到诊时间
    public static function repairRevisiting($hospital)
    {
        $project_id = self::getProject($hospital);
        $array = ClinicRecord::find()
            ->select(['max(clinic_time) as clinic_time ,patient_user_id'])
            ->where(['project_id' => $project_id])
            ->groupBy('patient_user_id')
            ->asArray()
            ->all();

        $array = array_column($array, null, 'patient_user_id');

        $userModelArray = User::find()
            ->select('id,last_revisiting_time')
            ->where(['project_id' => $project_id])
            ->all();

        foreach ($userModelArray as $model) {

            $new_time = $array[$model->id]['clinic_time'] ?? 0;
            if ($new_time > $model->last_revisiting_time) {
                $model->last_revisiting_time = $new_time;
                $model->save();
            }
        }

        return true;
    }

    /**
     * 断诊批量重置成,复诊
     *
     * @param $hospital
     */
    public static function resetFault($hospital)
    {
        $visit = self::getOutpatientType($hospital, 'referral');  //复诊
        $faultDiagnosis = self::getOutpatientType($hospital, 'break'); // 断诊
        $project_id = self::getProject($hospital);
        User::updateAll(['outpatient_type_id' => $visit], ['outpatient_type_id' => $faultDiagnosis, 'project_id' => $project_id]);

    }

    /**
     * 记录任务执行的日志
     * @param array $params
     */
    public static function errorLog(array $params)
    {
        $model = new HospitalLog();
        $params['content'] = isset($params['content']) ? json_encode($params['content']) : '';
        $params['remake'] = isset($params['remake']) ? json_encode($params['remake']) : '';
        $model->attributes = $params;
        $model->save();
    }

    /**
     * 定时任务检查
     */

    public static function monitoring()
    {
        $projectArray = [
            'hfx', 'hfy', 'sz', 'nt', 'nb', 'wz', 'hz', 'nc', 'gz', 'cs', 'hk', 'fy'
        ];

        $startTime = date('Y-m-d') . " 00:00:00";
        $endTime = date('Y-m-d') . " 23:59:59";

        $errorModel = HospitalLog::find()
            ->where(['hospital' => $projectArray, 'status' => -1])
            ->andWhere(['between', 'day', $startTime, $endTime])
            ->one();

        if ($errorModel) {
            $message = '项目:' . $errorModel->hospital . " " . $errorModel->function . ' 错误:' . $errorModel->content . ' 时间:' . $errorModel->day;
            $result = self::sendMessage($message, Yii::$app->params['DING_TOKEN'], Yii::$app->params['DING_KEY']);
            $resultArray = json_decode($result);

            if ($resultArray->errcode == '0') {
                HospitalLog::updateAll(['status' => 2], ['status' => -1]);
            }
        }
    }

    /**
     * 钉钉发送通知
     * @param $remote_server
     * @param $post_string
     * @return bool|string
     */
    public static function request_by_curl($remote_server, $post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    public static function sendMessage($message, $token, $key, $project_id = "")
    {
        $webhook = 'https://oapi.dingtalk.com/robot/send?access_token=' . $token;

        $t = time() * 1000;
        $ts = $t . "\n" . $key;
        $sig = hash_hmac('sha256', $ts, $key, true);
        $sig = base64_encode($sig);
        $sig = urlencode($sig);
        $webhook = $webhook . "&timestamp=" . $t . "&sign=" . $sig;

        $mobileArray = [];
        $userIdArray = [];

        if (!empty($project_id)) {
            // 存在项目,查询
           $memberArray = ProjectPrincipal::find()
                ->select('user_id,mobile')
                ->Where([
                    'or',
                    ['project_id' => $project_id],
                    ['name_sx' => $project_id]
                ])
                ->asArray()
                ->all();

           $mobileArray = array_column($memberArray,'mobile');
           $userIdArray = array_column($memberArray,'user_id');
        }

        $atArray = [];

        if (!empty($mobileArray)) {
            $atArray['atMobiles'] = $mobileArray;
        }

        if (!empty($userIdArray)) {
            $atArray['atUserIds'] = $userIdArray;
        }

        if (empty($mobileArray) && empty($userIdArray)) {
            $atArray['isAtAll'] = true;
        }

        $data = array('msgtype' => 'text', 'text' => array('content' => $message), 'at' => $atArray);

        $data_string = json_encode($data);

        $result = self::request_by_curl($webhook, $data_string);
        return $result;
    }

    /**
     * 临时修复,客服id与冗余字段不匹配问题
     */
    public static function repairMemberName($hospital)
    {

        $project_id = self::getProject($hospital);
        $array = User::find()
            ->select('m.id,m.realname')
            ->alias('u')
            ->where(['project_id' => $project_id])
            ->leftJoin(Member::tableName() . ' m', ' m.id = u.belong_member_id')
            ->groupBy('u.belong_member_id')
            ->asArray()
            ->all();

        foreach ($array as $value) {
            if (empty($value['id']) || empty($value['realname'])) {
                continue;
            }

            User::updateAll(['belong_member_name' => $value['realname']], ['belong_member_id' => $value['id']]);

        }

    }

    /**
     * 根据用户最新一条消费数据所在诊室,分配诊室(重构了,这个用不着了)
     * @param $hospital
     * @return bool
     */
    public static function updateClinic($hospital)
    {
        ini_set("memory_limit", "-1M");

        SectionList::$pix = $hospital;
        Expense::$pix = $hospital;
        $project_id = self::getProject($hospital);

        $sql = 'SELECT card_id,patient_name,event_time,`section` FROM (SELECT card_id,patient_name,event_time,`section`, `day` FROM ' . Expense::tableName() . ' ORDER BY `day` DESC limit 1000000 ) as e GROUP BY card_id ';
        // 查询最近一百万条消费记录中,有没有变更诊室的
        $allData = Yii::$app->db3->createCommand($sql)->queryAll();

        // 获取白友对应的,用户
        $allUser = User::find()
            ->select('id,patient_card_id as card_id,clinic_id')
            ->where(['project_id' => $project_id])
            ->asArray()
            ->all();
        $allUser = array_column($allUser, null, 'card_id');

        foreach ($allData as $value) {
            // 判断最新消费诊室与白友诊室是否相同,相同跳过

            $card_id = $value['card_id'];
            $clinic_id = self::getSection($value['section'], $hospital, 'clinic_id');

            //判断消费记录,有没有对应的用户
            if (!isset($allUser[$card_id])) {
                continue;
            }

            if ($clinic_id == $allUser[$card_id]['clinic_id']) {
                continue;
            }

            // 分配诊室后,分配跟换医助
            $assistantArray = self::getClinicRoom($hospital, $clinic_id);
            if ($assistantArray) {
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    $model = User::findOne($allUser[$card_id]['id']);
                    $model->clinic_id = $assistantArray['id'];
                    $model->belong_assistant_id = isset($assistantArray['member']) ? $assistantArray['member'][array_rand($assistantArray['member'])] : 0;

                    $by_clinic_nameArray = self::getClinicRoom($hospital, $allUser[$card_id]['clinic_id']);

                    $by_clinic_name = $by_clinic_nameArray['name'] ?? '';
                    $yy_clinic_name = $assistantArray['name'];

                    if ($model->save()) {
                        $operateModel = new OperateLog();
                        $operateModel->project_id = $project_id;
                        $operateModel->action_type = OperateLog::ACTION_TYPE_PATIENT_UPDATE;
                        $operateModel->patient_user_id = $allUser[$card_id]['id'];
                        $operateModel->action_content = '系统自动根据最近消费记录，将当前患者所在诊室【' . $by_clinic_name . '】自动调整为诊室【' . $yy_clinic_name . '】';
                        $operateModel->operate_name = '系统定时任务';
                        $operateModel->save();

                        // 记录医助归属人
                        $allocationArray = [
                            'project_id' => $model->project_id,
                            'patient_card_id' => $model->patient_card_id,
                            'member_id' => $model->belong_assistant_id,
                            'current_profession_id' => 1
                        ];
                        self::allocationRecord($allocationArray);
                    }

                    $transaction->commit();
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }

            // 分配诊室后,分配客服

        }

        return true;

    }

    /**
     * 添加医助
     * @param array $dataArray
     */
    public static function allocationRecord(array $dataArray)
    {
        // 添加医助记录记录
        $allocationModel = new AllocationRecord();
        $allocationModel->attributes = $dataArray;
        $allocationModel->save();
    }

    /**
     *
     */
    public static function excelTotal()
    {
        //项目
        $project_array = [
            '1' => 'hfy',
            '3' => 'hfx',
            '4' => 'sz',
            '5' => 'nb',
            '6' => 'cs',
            '7' => 'nc',
            '8' => 'wz',
            '9' => 'nt',
            '10' => 'gz',
            '12' => 'hz',
            '18' => 'fy'
        ];


        $day = date("Y-m-d");
        $day_start = strtotime($day);
        $day_end = strtotime($day . ' 23:59:59');

        # 1. 获取当天最新挂号时间
        $query_reg = User::find()
            ->select('project_id,reg_time')
            ->where(['and',
                ['between', 'created_at', $day_start, $day_end],
                ['between', 'reg_time', $day_start, $day_end],
            ])
            ->limit(1000)
            ->orderBy(['reg_time' => SORT_DESC])->createCommand()->getRawSql();

        $sql_reg = 'SELECT project_id,FROM_UNIXTIME(`reg_time`, "%Y-%m-%d %H:%i") reg_time FROM (' . $query_reg . ') as e GROUP BY project_id ';
        $reg_array = Yii::$app->db->createCommand($sql_reg)->queryAll();
        $reg_array = array_column($reg_array, null, 'project_id');

        # 2. 获取当天最新消费 插入时间
        $query_consumption = Consumption::find()
            ->select('project_id,created_at')
            ->where(['and',
                ['between', 'created_at', $day_start, $day_end],
                ['between', 'clinic_time', $day_start, $day_end],
            ])
            ->limit(1000)
            ->orderBy(['created_at' => SORT_DESC])->createCommand()->getRawSql();

        $sql_consumption = 'SELECT project_id,FROM_UNIXTIME(`created_at`, "%Y-%m-%d %H:%i") created_at FROM (' . $query_consumption . ') as e GROUP BY project_id ';
        $consumption_array = Yii::$app->db->createCommand($sql_consumption)->queryAll();
        $consumption_array = array_column($consumption_array, null, 'project_id');


        # 3. 获取最后一次文件上传时间
        # 2. 获取当天最新消费 插入时间
        $query_doc = DocumentList::find()
            ->select('project_name,created_time')
            ->where(['and',
                ['between', 'created_time', $day_start, $day_end],
            ])
            ->limit(1000)
            ->orderBy(['created_time' => SORT_DESC])->createCommand()->getRawSql();

        $sql_doc = 'SELECT project_name,FROM_UNIXTIME(`created_time`, "%Y-%m-%d %H:%i") created_time FROM (' . $query_doc . ') as e GROUP BY project_name ';
        $doc_array = Yii::$app->db3->createCommand($sql_doc)->queryAll();
        $doc_array = array_column($doc_array, null, 'project_name');


        $messageArray = [];

        foreach ($project_array as $key => $value) {
            $message = '';
            $message .= env($value);
            $message .= '：';
            // 最后一次文件上传时间
            $doc_time = $doc_array[$value]['created_time'] ?? '无';
            // 最后一次挂号时间
            $reg_time = $reg_array[$key]['reg_time'] ?? '无';
            // 最后一次新增消费记录时间
            $consumption_time = $consumption_array[$key]['created_at'] ?? '无';

            $type = 0;
            if ($doc_time == '无' && $reg_time == '无' && $consumption_time == '无') {
                $message .= '今日未上传文件';
            } elseif ($reg_time == '无' && $consumption_time == '无') {
                $message .= '今日未上传有效文件';
            } else {
                $type = 1;
                $message .= '最近一次上传时间: ' . $doc_time;
                $message .= ' | ' . '最近一次挂号时间: ' . $reg_time;
                $message .= ' | ' . '最近一次新增消费记录时间: ' . $consumption_time;
            }

            if ($type == 1) {
                array_unshift($messageArray, $message);
            } else {
                $messageArray[] = $message;
            }

        }

        $message = '';
        foreach ($messageArray as $value) {
            $message .= $value . PHP_EOL . PHP_EOL;
        }

        self::sendMessage($message, Yii::$app->params['DING_TOKEN'], Yii::$app->params['DING_KEY']);
        return true;
    }

    /**
     * 同步近30天奕远-白友的数据
     * @param $hospital
     * @return bool
     * @throws Exception
     */
    public static function repairHistory($hospital)
    {
        RegistrationList::$pix = $hospital;
        Expense::$pix = $hospital;
        $project_id = self::getProject($hospital);
        $day_end = strtotime(date('Y-m-d') . '23:59:59');
        $day_start = $day_end + 1 - 30 * 24 * 60 * 60;

        # 1.获取白友-奕远用户数量
        // 白友挂号记录
        $b_userCountArray = User::find()
            ->select(['FROM_UNIXTIME(`reg_time`, "%Y-%m-%d") reg_day', 'count(*) as count'])
            ->where(['project_id' => $project_id])
            ->andWhere(['between', 'reg_time', $day_start, $day_end])
            ->groupBy('reg_day')
            ->asArray()
            ->all();
        $b_userCountArray = array_column($b_userCountArray, null, 'reg_day');

        // 奕远挂号记录
        $y_userCountArray = RegistrationList::find()
            ->select(['date(registration_time) AS reg_day', 'count(*) as count'])
            ->where([
                'or',
                ['between', 'registration_time', date("Y-m-d H:i:s", $day_start), date("Y-m-d H:i:s", $day_end)],
                ['between', 'created_time', $day_start, $day_end]
            ])
            ->groupBy('reg_day')
            ->asArray()
            ->all();
        $y_userCountArray = array_column($y_userCountArray, null, 'reg_day');

        # 2.获取白友-奕远消费数据
        // 白友消费记录
        $b_consumptionCountArray = ConsumptionDetail::find()
            ->select(['FROM_UNIXTIME(`event_at`, "%Y-%m-%d") clinic_day', 'count(*) as count'])
            ->where(['project_id' => self::getProject($hospital)])
            ->andWhere(['between', 'event_at', $day_start, $day_end])
            ->groupBy('clinic_day')
            ->asArray()
            ->all();
        $b_consumptionCountArray = array_column($b_consumptionCountArray, null, 'clinic_day');

        // 奕远消费记录
        $y_consumptionCountArray = Expense::find()
            ->select(['FROM_UNIXTIME(`day`, "%Y-%m-%d") clinic_day', 'count(*) as count'])
            ->where(['between', 'day', $day_start, $day_end])
            ->groupBy('clinic_day')
            ->asArray()
            ->all();
        $y_consumptionCountArray = array_column($y_consumptionCountArray, null, 'clinic_day');        //用户数量

        $diffUserArray = [];
        $diffConsumptionArray = [];
        $is_user = 0;
        for ($i = 0; $i < 30; $i++) {
            $reg_day = date('Y-m-d', $day_start + $i * 24 * 60 * 60);
            $b_userCount = $b_userCountArray[$reg_day]['count'] ?? 0;
            $y_userCount = $y_userCountArray[$reg_day]['count'] ?? 0;
            $b_consumptionCount = $b_consumptionCountArray[$reg_day]['count'] ?? 0;
            $y_consumptionCount = $y_consumptionCountArray[$reg_day]['count'] ?? 0;
            // 如果白友与奕远用户数据不一致,同步一下
            if ($b_userCount != $y_userCount) {
                $is_user = 1;
                $diffUserArray[$reg_day] = [
                    'day' => $reg_day,
                    'b_count' => $b_userCount,
                    'y_count' => $y_userCount
                ];
            }

            // 如果白友与奕远消费数据不一致,同步一下
            if ($b_consumptionCount != $y_consumptionCount) {
                $diffConsumptionArray[$reg_day] = [
                    'day' => $reg_day,
                    'b_count' => $b_consumptionCount,
                    'y_count' => $y_consumptionCount
                ];
            }
        }

        $model = new HistoryLog();
        $model->day = date('Y-m-d H:i:s');
        $model->user_content = json_encode($diffUserArray);
        $model->consumption_content = json_encode($diffConsumptionArray);
        $model->save();

        // 修复30天缺少入院/出院记录导致的问题
        ExcelExtendService::updateOutHospitalRecord(date('Y-m-d', $day_start), date('Y-m-d', $day_end), $hospital);

        if ($is_user == 1) {
            // 运行,添加用户脚本
            self::registration($hospital);
        }

        foreach ($diffConsumptionArray as $key => $value) {
            // 运行,添加消费记录脚本
            self::updateTimeData($hospital, $key, $key);
        }

        return true;
    }

    // 挂号数据最新 id
    public static function registeredSerialNo($ProjectId)
    {
        $projectModel = Project::findOne($ProjectId);

        RegistrationList::$pix = $projectModel->name_sx;

        $serialArray = RegistrationList::find()
            ->orderBy(['registration_time' => SORT_DESC])
            ->limit(1)
            ->asArray()
            ->one();
        if (empty($serialArray)) {
            return '';
        }
        $serial_no = date('Y-m-d H:i', strtotime($serialArray['registration_time']));

        return $serial_no;
    }

    /**
     * 添加奕远挂号数据
     * @param $params
     * @return bool
     */
    public static function registeredUser($params)
    {
        $name_sx = self::getRedisProject($params['ProjectId']);
        RegistrationList::$pix = $name_sx;
        SectionList::$pix = $name_sx;

        // 如果状态是复诊 且是有效状态,判断之前有没有有效状态
        if ($params['RegisterSort'] != 10 && $params['State'] == 200) {
            // 复诊判断
            $exists = RegistrationList::find()
                ->where([
                    'and',
                    ['card_id' => $params['CardNo']],
                    ['state' => [0, 200]]
                ])->exists();

            if ($exists) {
                return true;
            }

        } elseif ($params['RegisterSort'] != 10 && $params['State'] != 200) {

            $exists = RegistrationList::find()
                ->where([
                    'and',
                    ['serial_no' => $params['SerialNo']]
                ])->exists();

            if (!$exists) {
                return true;
            }
        }

        $model = RegistrationList::find()
            ->where([
                'and',
                ['serial_no' => $params['SerialNo']]
            ])->one();

        $repeat = RegistrationList::find()
            ->select('card_id, truename')
            ->where([
                'and',
                ['state' => 200],
                ['card_id' => $params['CardNo']],
                ['!=', 'serial_no', $params['SerialNo']]
            ])->one();


        $is_new = 0;
        if ($model) {
            $is_new = 1;
        } else {
            $model = new RegistrationList();
        }

        $is_dengta = false;

        if ($is_new == 0 && $repeat && $params['State'] == 200) {
            $message = '项目：' . Yii::$app->params[$name_sx] . PHP_EOL .
                '患者A：' . $params['InvalidName'] . '/' . $params['CardNo'] . " 与 患者B：" . $repeat->truename . "/" . $repeat->card_id . '诊疗号重复' . PHP_EOL .
                '-----------------------------' . PHP_EOL .
                '请' . Yii::$app->params[$name_sx] . '负责人尽快修改患者B诊疗号。' . PHP_EOL . '如需修改患者A诊疗号，修改完成后请尽快联系技术人员修复白友数据';
            self::sendMessage($message, Yii::$app->params['DING_TOKEN_REPEAT'], Yii::$app->params['DING_KEY_REPEAT'],$params['ProjectId']);
        } else {
            $is_dengta = true;
        }

        if ($is_new == 1 && $model->state == $params['State']) {
            return true;
        }

        $sectionInfo = self::getRedisSection($name_sx, $params['RegisterObjName']);

        $model->state = $params['State'];

        if ($is_new == 0) {
            $params['MTPhoneNo'] = str_replace(' ', '', $params['MTPhoneNo']);
            $params['MTPhoneNo'] = str_replace('.', '', $params['MTPhoneNo']);
            $params['PhoneNO'] = str_replace(' ', '', $params['PhoneNO']);
            $params['PhoneNO'] = str_replace('.', '', $params['PhoneNO']);
            $model->serial_no = $params['SerialNo'];
            $model->truename = $params['InvalidName'];
            $model->city = $params['WorkUnit'] ?? '';
            $model->sex = $params['InvalidSex'] ? '女' : '男';
            $model->birthday = date('Y-m-d H:i:s', strtotime($params['BirthDate']));
            $model->registration_time = date('Y-m-d H:i:s', strtotime($params['EnregisterTime']));
            $model->section = $sectionInfo[$params['RegisterObjName']];
            $model->doctor_name = $params['DoctorName'];
            $model->registration_fee = $params['RegisterMoney'] ?? 0;
            $model->card_id = $params['CardNo'];
            $model->message_source = $params['ApproachName'];
            $model->address = $params['Address'];
            $model->mobile = !empty($params['MTPhoneNo']) ? $params['MTPhoneNo'] : $params['PhoneNO'];
            $model->phone = $model->mobile;
            $model->created_time = time();
        } elseif ($is_new == 1) {
            $model->updated_time = time();
        }

        $sectionModel = SectionList::findOne($model->section);
        if ($is_dengta && !empty($sectionModel->clinic_name) && !empty($model->mobile)) {
            self::dengtaPatientUser([
                'name_sx' => $name_sx,
                'mobile' => $model->mobile,
                'clinic_name' => $sectionModel->clinic_name,
                'revisiting_time' => strtotime($params['EnregisterTime']),
            ]);
        }

        if ($model->save()) {
            return true;
        } else {
            return $model->errors;
        }

    }


    // 消费数据最新 id
    public static function expenseSerialNo($ProjectId, $type)
    {
        $projectModel = Project::findOne($ProjectId);
        Expense::$pix = $projectModel->name_sx;

        $serialArray = Expense::find()
            ->where(['type' => $type])
            ->limit(1)
            ->orderBy(['event_time' => SORT_DESC])
            //    ->orderBy(['entry_time' => SORT_DESC])
            ->asArray()
            ->one();

        //   $serial_no = date('Y-m-d H:i',strtotime($serialArray['entry_time']) );
        if (empty($serialArray)) {
            return '';
        }

        if ($type == 0) {
            $serial_no = date('Y-m-d H:i', strtotime($serialArray['event_time']));
        } else {
            $serial_no = date('Y-m-d 00:00', strtotime($serialArray['event_time']));
        }

        return $serial_no;
    }

    /**
     * 添加奕远消费数据
     * @param $params
     * @return bool
     */
    public static function expenseAdd($params)
    {
        $type = $params['type'];
        $name_sx = self::getRedisProject($params['ProjectId']);
        Expense::$pix = $name_sx;
        SectionList::$pix = $name_sx;

        $exists = Expense::find()
            ->where([
                'and',
                ['serial_no' => $params['SerialNo']],
                ['type' => $type],
            ])->exists();

        if ($exists) {
            return true;
        }

        $sectionName = isset($params['AcceptSectionName']) ? $params['AcceptSectionName'] : $params['SectionName'];
        $sectionInfo = self::getRedisSection($name_sx, $sectionName);
        $model = new Expense();
        $model->serial_no = $params['SerialNo'];
        $model->patient_name = $params['InvalidName'];
        $model->card_id = $params['CardNo'];
        $model->drug = $params['ItemName'];
        $model->unit = $params['ItemUnit'];
        $model->count = $params['Amount'];
//        $model->price = $params['SellingPrice'];
//        $model->sales_money = $params['SellingAmount'];
//        $model->discounted_money = $params['AdvantagedMoney'];
        $model->price = 0;
        $model->sales_money = 0;
        $model->discounted_money = 0;

        $model->money_name = $params['CategoryAName'];
        $model->event_time = $type ? date('Y-m-d H:i:s', strtotime($params['BefellTime'])) : date('Y-m-d H:i:s', strtotime($params['ChargeTime']));
//        $model->entry_time = date('Y-m-d H:i:s',strtotime($params['BefellTime'])); 发生时间
        $model->section = $sectionInfo[$sectionName];
        $model->doctor_name = $params['DoctorName'];
        $model->type = $params['type'];
        $model->day = $type ? strtotime(date('Y-m-d', strtotime($params['BefellTime']))) : strtotime(date('Y-m-d', strtotime($params['ChargeTime'])));
        $model->created_at = time();

        if ($model->save()) {
            return true;
        } else {
            return $model->errors;
        }

    }

    /**
     * 获取上次住院/出院时间
     *
     * @param $ProjectId
     * @param $type
     * @return int|mixed
     */
    public static function inHospitalSerialNo($ProjectId, $type)
    {
//        $serialArray = InHospital::find()
//            ->where(['type' => $type,'project_id' => $ProjectId])
//            ->limit(1)
//            ->orderBy(['event_time' => SORT_DESC])
//            ->asArray()
//            ->one();

        //      return $serialArray['day'] ?? 0;

        return date('Y-m-d') . ' 00:00:00';
    }


    /**
     * 存入住院出院数据
     * @param $params
     * @return bool
     */
    public static function inHospital($params)
    {
        $serial_no = $params['SerialNo'];
        $project_id = $params['ProjectId'];
        if ($params['type'] == 1) {
            $time = $params['EnregisterTime'];
        } elseif ($params['type'] == 2) {
            $time = $params['EnregeditTime'];
        } else {
            $time = 0;
        }

        $model = InHospital::find()
            ->where(['project_id' => $project_id, 'serial_no' => $serial_no, 'type' => $params['type']])
            ->one();

        if (!$model) {
            $model = new InHospital();
        } elseif ($model->event_time == strtotime($time)) { // 住院/出院时间一致,不修改
            return true;
        }

        $model->project_id = $project_id;
        $model->card_id = $params['CardNo'];
        $model->serial_no = $serial_no;
        $model->type = $params['type'];
        $model->clinic_name = $params['SectionName'] ?? '';
        $model->day = $time;
        $model->event_time = strtotime($time);
        $model->save();
        return true;
    }

    /**
     * 中转库更新用户
     * @param $params
     * @return array|bool
     */
    public static function updateRegistration($params)
    {
        $name_sx = self::getRedisProject($params['ProjectId']);
        RegistrationList::$pix = $name_sx;
        SectionList::$pix = $name_sx;
        /**
         * @var RegistrationList $model
         */
        $model = RegistrationList::find()
            ->where([
                'and',
                ['serial_no' => $params['SerialNo']]
            ])->one();
        if (!$model) {
            // 新用户跳过
            return true;
        }

        // 更改的参数个数
        $change_num = 0;
        $sex = $params['InvalidSex'] ? '女' : '男';
        $birthday = date('Y-m-d H:i:s', strtotime($params['BirthDate']));
        $registration_time = date('Y-m-d H:i:s', strtotime($params['EnregisterTime']));
        $params['MTPhoneNo'] = str_replace(' ', '', $params['MTPhoneNo']);
        $params['MTPhoneNo'] = str_replace('.', '', $params['MTPhoneNo']);
        $params['PhoneNO'] = str_replace(' ', '', $params['PhoneNO']);
        $params['PhoneNO'] = str_replace('.', '', $params['PhoneNO']);
        $phone = !empty($params['MTPhoneNo']) ? $params['MTPhoneNo'] : $params['PhoneNO'];
        $WorkUnit = $params['WorkUnit'] ?? '';
        // 1.更新中转库挂号用户数据
        $model->truename != $params['InvalidName'] ? ($model->truename = $params['InvalidName']) . ($change_num++) : '';
        $model->sex != $sex ? ($model->sex = $sex) . ($change_num++) : '';
        $model->birthday != $birthday ? ($model->birthday = $birthday) . ($change_num++) : '';
        $model->registration_time != $registration_time ? ($model->registration_time = $registration_time) . ($change_num++) : '';
        $model->card_id != $params['CardNo'] ? ($model->card_id = $params['CardNo']) . ($change_num++) : '';
        $model->address != $params['Address'] ? ($model->address = $params['Address']) . ($change_num++) : '';
        $model->city != $WorkUnit ? ($model->city = $WorkUnit) . ($change_num++) : '';
        $model->mobile != $phone ? ($model->mobile = $phone) . ($change_num++) : '';
        $model->registration_fee != $params['RegisterMoney'] ? ($model->registration_fee = $params['RegisterMoney']) . ($change_num++) : '';
        $model->state != $params['State'] ? ($model->state = $params['State']) . ($change_num++) : '';;
        $model->phone != $phone ? ($model->phone = $phone) . ($change_num++) : '';
        $model->updated_time = time();
        if ($change_num > 0 && $model->save()) {
            // 2.更新白友患者
            /**
             * @var User $patient
             */
            $patient = User::find()
                ->where(['serial_no' => $params['SerialNo'], 'project_id' => $params['ProjectId']])
                ->andWhere(['>', 'serial_no', 0])
                ->one();
            if (empty($patient)) {
                return true;
            }
            $oldPatient = new User();
            $oldPatient->setAttributes($patient->getAttributes());
            $patient->name = $model->truename;
            $patient->patient_card_id = $model->card_id;
            $patient->mobile = $model->phone;
            $patient->birthday = $model->birthday;
            $patient->age = $model->birthday ? (date('Y') - date('Y', strtotime($model->birthday))) : 0;
            $patient->reg_time = strtotime($registration_time);
            $patient->gender = self::getGender($model->sex);
            $patient->address = $model->address;
            $patient->status = $model->state == 200 ? User::STATUS_ENABLE : User::STATUS_DELETE;
            $patient->saveAndCheckResult();

            // 3.新增or更新挂号费
            $registerModel = RegisterFee::findOne([
                'serial_no' => $params['SerialNo'],
                'project_id' => $params['ProjectId'],
            ]);
            if (empty($registerModel) && $model->registration_fee > 0) {
                $registerModel = new RegisterFee();
                $registerModel->project_id = $params['ProjectId'];
                $registerModel->serial_no = $params['SerialNo'];
            }
            if ($registerModel) {
                $registerModel->patient_card_id = $model->card_id;
                $registerModel->register_fee = $model->registration_fee;
                $registerModel->yy_clinic_id = $model->section;
                $registerModel->yy_clinic_name = self::getSection($model->section, $name_sx, 'section');
                $registerModel->clinic_id = self::getSection($model->section, $name_sx, 'clinic_id');
                $registerModel->registration_time = strtotime($registration_time);
                $registerModel->status = $model->state == 200 ? RegisterFee::TYPE_REGISTER : RegisterFee::TYPE_REGISTER_OUT;
                $registerModel->saveAndCheckResult();
            }
            // 4-1.患者编辑日志
            PatientOperateLogService::create($patient->project_id, $patient->id, OperateLog::ACTION_TYPE_HOSPITAL_PATIENT_UPDATE, PatientOperateLogService::getPatientChangeLog($patient, $oldPatient), 1);
            // 4-2.用户操作日志
            MemberOperateLogService::createHospitalLog('update', $patient, $oldPatient);

            return true;
        }
        return $model->errors;
    }

    // 更新消费记录的卡号
    public static function updateExpense($params)
    {
        $name_sx = self::getRedisProject($params['ProjectId']);
        $type = $params['type'];

        Expense::$pix = $name_sx;

        $model = Expense::find()
            ->where([
                'and',
                ['serial_no' => $params['SerialNo']],
                ['type' => $type],
            ])->one();

        if (!$model) {
            return true;
        }

        if ($model->card_id != $params['CardNo']) {

            $model->card_id = $params['CardNo'];
            $model->save();

            // 更新白友消费详情 诊疗号
            $ConsumptionDetailModel = ConsumptionDetail::find()
                ->where([
                    'project_id' => $params['ProjectId'],
                    'yiyuan_aid' => $model->id,
                ])
                ->one();

            $ConsumptionDetailModel->patient_card_id = $params['CardNo'];
            $ConsumptionDetailModel->save();

            // 更新消费汇总 诊疗号
            $ConsumptionModel = Consumption::findOne($ConsumptionDetailModel->consumption_id);
            $ConsumptionModel->patient_card_id = $params['CardNo'];
            $ConsumptionModel->save();

        }
        return true;
    }


    /**
     * @apiName 从redis中获取 项目缩写
     * @param $project
     * @return mixed|string
     * @author loujie
     */
    public static function getRedisProject($project)
    {
        $redis = Yii::$app->redis;
        $key = 'hospital-project';
        $name_sx = $redis->hget($key, $project);

        if (!$name_sx) {
            $projectModel = Project::findOne($project);
            $redis->hset($key, $project, $projectModel->name_sx);
            $name_sx = $projectModel->name_sx;
        }

        return $name_sx;
    }

    /**
     * @apiName 从redis中获取诊室信息
     * @param $name_sx
     * @param $SectionName
     * @return array|false|string|\yii\db\ActiveRecord[]
     * @author loujie
     */
    public static function getRedisSection($name_sx, $SectionName)
    {
        $redis = Yii::$app->redis;
        $key = 'hospital-section';
        SectionList::$pix = $name_sx;

        // 从redis中取出输入
        $sectionStr = $redis->hget($key, $name_sx);

        if (!$sectionStr) {
            $sectionInfo = SectionList::find()
                ->asArray()
                ->all();
            $sectionInfo = array_column($sectionInfo, 'id', 'section');
        } else {
            $sectionInfo = json_decode($sectionStr, true);
        }

        if (!isset($sectionInfo[$SectionName]) && !empty($SectionName)) {
            $listModel = new SectionList();
            $listModel->section = $SectionName;
            $listModel->created_at = date("Y-m-d H:i:s");
            // 创建的时候可以添加钉钉推送
            $listModel->save();

            $message = '项目：' . Yii::$app->params[$name_sx] . PHP_EOL .
                '添加了新诊室：' . $SectionName . ' 。请及时与开发人员确认新诊室信息';
            $result = self::sendMessage($message, Yii::$app->params['DING_TOKEN_CLINIC'], Yii::$app->params['DING_KEY_CLINIC']);

            $sectionInfo = SectionList::find()
                ->asArray()
                ->all();
            $sectionInfo = array_column($sectionInfo, 'id', 'section');
            $redis->hset($key, $name_sx, json_encode($sectionInfo, true));
        }

        return $sectionInfo;
    }

    /**
     * @apiName 处理
     * @apiGroup
     * @apiParam {Number}
     * @apiParam {String}
     * @param $WorkUnit
     * @return int|mixed
     * @author loujie
     */
    public static function dealCity($WorkUnit)
    {
        $city_id = 0;
        $city_name = '';

        if (empty($WorkUnit)) {
            return [
                'city_id' => $city_id,
                'city_name' => $city_name
            ];
        }

        $url = 'https://restapi.amap.com/v3/geocode/geo?key=' . Yii::$app->params['amap.key'] . '&address=' . $WorkUnit;
        $cityJson = CommonHelper::https_request($url);
        $cityArray = json_decode($cityJson, true);
        $city_id = $cityArray['geocodes']['0']['adcode'] ?? 0;

        if ($city_id > 0) {
            // province(省) city(市) district(区)
            if (!empty($cityArray['geocodes']['0']['district'])) {
                $city_name = $cityArray['geocodes']['0']['district'];
            } elseif (!empty($cityArray['geocodes']['0']['city'])) {
                $city_name = $cityArray['geocodes']['0']['city'];
            } else {
                $city_name = $cityArray['geocodes']['0']['province'];
            }
        }

        if (is_array($city_name)) {
            $city_name = '';
        }

//        if ($city_id == 0) {
//
//            #匹配规则
//
//            if (strpos($WorkUnit,'区') && strpos($WorkUnit,'市')) {// 市 , 区
//                $city_name = self::cut('市','区',$WorkUnit) . '区';
//                $city_id = self::getRedisCity($city_name);
//
//            } elseif (strpos($WorkUnit,'县') && strpos($WorkUnit,'市')) {// 市 , 县
//
//                $city_name = self::cut('市','县',$WorkUnit)  . '县';
//                $city_id = self::getRedisCity($city_name);
//
//            }elseif (strpos($WorkUnit,'省') && strpos($WorkUnit,'市')) { // 省,市
//                $city_name = self::cut('省', '市', $WorkUnit) . '市'; //
//                $city_id = self::getRedisCity($city_name);
//
//            }elseif (strpos($WorkUnit,'省') && strpos($WorkUnit,'区')) { // 省,区
//                $city_name = self::cut('省','区',$WorkUnit)  . '区'; //
//                $city_id = self::getRedisCity($city_name);
//                print_r(3451);die();
//
//            }elseif (strpos($WorkUnit,'省') && strpos($WorkUnit,'县')) { // 省,县
//                $city_name = self::cut('省','县',$WorkUnit)  . '县'; //
//                $city_id = self::getRedisCity($city_name);
//
//            } elseif (strpos($WorkUnit,'省')) { // 省
//                $city_name = self::cut('', '省', $WorkUnit) . '省';
//                $city_id = self::getRedisCity($city_name);
//
//            }elseif (strpos($WorkUnit,'市')) {// 市 , 市 / 市
//
//                $count = substr_count($WorkUnit,'市');
//                $city_name = self::cut( $count == 1 ? '' : '市' , '市', $WorkUnit) . '市';
//                $city_id = self::getRedisCity($city_name);
//
//            }elseif (strpos($WorkUnit,'县')) {
//                $city_name = self::cut('','县',$WorkUnit)  . '县'; // 县
//                $city_id = self::getRedisCity($city_name);
//            }
//
//            if ($city_id == 0) {
//                $city_name = '';
//            }
//
//        }


        return [
            'city_id' => $city_id,
            'city_name' => $city_name
        ];
    }

    /**
     * php截取指定两个字符之间字符串，默认字符集为utf-8 Power by 大耳朵图图
     * @param string $begin 开始字符串
     * @param string $end 结束字符串
     * @param string $str 需要截取的字符串
     * @return string
     */
    public static function cut($begin, $end, $str)
    {

        if (empty($begin)) {
            $b = 0;
            $e = mb_strpos($str, $end);

        } else {
            $b = mb_strpos($str, $begin) + mb_strlen($begin);
            $e = mb_strpos($str, $end) - $b;
        }


        return mb_substr($str, $b, $e);
    }

    /**
     * @apiName 根据城市名获取,城市id
     * @param $city_name
     * @return int|mixed
     */
    public static function getRedisCity($city_name)
    {
        $redis = Yii::$app->redis;
        $key = 'hospital-city';

        $city_id = $redis->hget($key, $city_name);

        if (!is_numeric($city_id)) {
            // 从数据库里查询 插入redis
            $provincesModel = Provinces::find()
                ->select('id,title')
                ->where(['title' => $city_name])
                ->one();
            if ($provincesModel) {
                $redis->hset($key, $city_name, $provincesModel->id);
                $city_id = $provincesModel->id;
            } else {
                $city_id = 0;
            }
        }

        return $city_id;

    }

    /**
     * @apiName 添加灯塔 项目科室为植发的数据 (姓名、性别、年龄、诊疗号、诊室、到诊时间、电话、微信、城市、病种、备注)
     * @apiGroup
     * @param $params
     * @apiParam {Number} relation_baiyou_pname   项目缩写
     *                    patient_card_id  诊疗号
     *                    age   年龄
     *                    last_revisiting_time  上次到诊时间
     *                    wx_name  微信号
     *                    city_id  城市id
     * @apiParam {String} name  姓名
     *                    clinic_name  诊室名
     *                    city_name 城市名
     *                    diseases_name  病种名
     *                    remark  备注
     *                    mobile  手机号
     * @return bool
     * @throws HttpException
     * @author loujie
     */
    public static function addDengtaPatient($params)
    {
        if (empty($params['patient_card_id'])) {
            throw new HttpException(422, '诊疗号不能为空');
        }

        // 获取项目
        $project_id = self::getProject($params['relation_baiyou_pname']);

        // 查询用户
        $model = User::findOne([
            'patient_card_id' => $params['patient_card_id'],
            'project_id' => $project_id
        ]);
        $old_clinic = 0;
        if (empty($model)) {
            $model = new User();
        } else {
            $old_clinic = $model->clinic_id;
        }

        // 计算生日
        if (isset($params['age']) && $params['age'] > 0) {
            $params['birthday'] = date("Y-01-01", strtotime("-" . $params['age'] . " year"));;
        }

        // 获取诊室
        $clinic_id = Clinic::find()->select('id')->where(['name' => $params['clinic_name'], 'project_id' => $project_id, 'status' => Clinic::STATUS_ENABLE])->scalar();

        // 1.新增or更新患者
        $model->attributes = $params;
        $model->project_id = $project_id;
        $model->clinic_id = $clinic_id ?: 0;
        $model->reg_time = $params['last_revisiting_time'];
        $model->patient_diseases_id = 0;
        $model->serial_no = User::SERIAL_NO_DT;
        // nczf数据用不到就诊类型，目前逻辑客服患者列表基于就诊类型来的，所以默认当月数据当初诊处理。否则植发项目客服患者列表将无数据
        $model->outpatient_type_id = OutpatientType::ID_FIRST_VISIT;
        // 分配医助
        $allocationArray = [];
        if (empty($clinic_id) || $old_clinic != $model->clinic_id) {
            $assistantArray = self::getClinicRoom($params['relation_baiyou_pname'], $clinic_id);
            if ($assistantArray) {
                $model->clinic_id = $assistantArray['id'];
                $model->belong_assistant_id = isset($assistantArray['member']) ? $assistantArray['member'][array_rand($assistantArray['member'])] : 0;

                $allocationArray = [
                    'project_id' => $model->project_id,
                    'patient_card_id' => $model->patient_card_id,
                    'member_id' => $model->belong_assistant_id,
                    'current_profession_id' => 1
                ];
            }
        }
        $model->saveAndCheckResult();

        // 2.添加医助变更记录
        if ($allocationArray) {
            self::allocationRecord($allocationArray);
        }
        return true;
    }


    /**
     * @apiName  添加回访记录
     * @apiGroup
     * @apiParam {Number}
     *
     * relation_baiyou_pname  项目缩写
     * patient_card_id 患者诊疗号
     * callback_state_id  回访状态ID（关联by_marketing_callback_status表）
     * dt_callback_id 灯塔回访表 id
     * callback_way_name 回访方式【1：电话、2：微信、3：QQ、4：其它】
     * content  回访内容
     * current_callback_time 本次回访时间
     * next_callback_time  下次回访时间
     * next_fuzhen_time 下次复诊时间
     * member_id  回访人ID【member表ID】
     * member_name 回访人姓名
     * outpatient_type_id  就诊类型（关联by_marketing_outpatient_type）  // 全部按照流失算
     * @apiParam {String}
     *
     * @author loujie
     */
    public static function addDengtaCallback($params)
    {
        // 获取项目
        $project_id = self::getProject($params['relation_baiyou_pname']);
        $dt_callback_id = $params['dt_callback_id'] ?? 0;
        $exists = Callback::find()->where(['dt_callback_id' => $dt_callback_id])->exists();
        if ($exists) {
            throw new HttpException(422, '该回访记录已存在');
        }

        // 患者诊疗号->患者id
        $patient_user_id = User::find()->select('id')->where(['project_id' => $project_id, 'patient_card_id' => $params['patient_card_id'], 'status' => User::STATUS_ENABLE])->scalar();
        if (empty($patient_user_id)) {
            throw new HttpException(422, '患者不存在');
        }

        $params['patient_user_id'] = $patient_user_id;
        // 对应回访状态
        $params['callback_state_id'] = CallbackStatus::DT_STATUS[$params['callback_state_id']];
        $params['callback_state'] = CallbackStatus::STATUS_NAME[$params['callback_state_id']];
        // 对应回访方式
        $params['callback_way_id'] = Callback::WAY_CALLBACK[$params['callback_way_name']];

        $model = new Callback();
        $model->attributes = $params;
        $model->project_id = $project_id;
        $model->dt_callback_id = $dt_callback_id;
        $model->outpatient_type_id = OutpatientType::ID_FIRST_VISIT;
        $model->member_id = 0;
        $model->member_name = '灯塔咨询';
        $model->saveAndCheckResult();

        return true;

    }
//    /**
//     * 过来的数据卡号唯一
//     * @param int $type 1 = 非重复  2 = 重复
//     * @param $name_sx 项目缩写
//     */
//    public static function cardCheck($name_sx,$type = 1)
//    {
//        // 获取1-5月份更新的数据,查询
//        if ($type == 1) {
//            $sql = 'select * from by_temp_'.$name_sx.' group by CardNo HAVING count(*) = 1';
//        } else {
//            $sql = 'SELECT * from  by_temp_'.$name_sx.' WHERE CardNo in (select CardNo from  by_temp_'.$name_sx.' group by CardNo HAVING count(*) > 1 ) ORDER BY State ASC';
//        }
//
//        $data = Yii::$app->db3->createCommand($sql)->queryAll();
//
//        RegistrationList::$pix = $name_sx;
//        foreach ($data as $item) {
//
//            $model = RegistrationList::find()
//                ->where(['card_id' => $item['CardNo']])
//                ->one();
//
//            // 没有的用户添加用户
//            if (!$model) {
//
//                $sectionInfo = self::getRedisSection($name_sx,$item['RegisterObjName']);
//                $model = new RegistrationList();
//                $item['MTPhoneNo'] = str_replace(' ','',$item['MTPhoneNo']);
//                $item['MTPhoneNo'] = str_replace('.','',$item['MTPhoneNo']);
//                $item['PhoneNO'] = str_replace(' ','',$item['PhoneNO']);
//                $item['PhoneNO'] = str_replace('.','',$item['PhoneNO']);
//                $model->serial_no = $item['SerialNo'];
//                $model->truename = $item['InvalidName'];
//                $model->sex = $item['InvalidSex'] ? '女' : '男';
//                $model->birthday = date('Y-m-d H:i:s',strtotime($item['BirthDate']));
//                $model->registration_time = date('Y-m-d H:i:s',strtotime($item['EnregisterTime']));
//                $model->section = $sectionInfo[$item['RegisterObjName']];
//                $model->doctor_name = $item['DoctorName'];
//                $model->card_id = $item['CardNo'];
//                $model->message_source = $item['ApproachName'];
//                $model->address = $item['Address'];
//                $model->mobile = !empty($item['MTPhoneNo']) ? $item['MTPhoneNo'] : $item['PhoneNO'] ;
//                $model->phone = $model->mobile;
//                $model->state = $item['State'];
//                $model->created_time = time();
//                $model->save();
//                continue;
//            }
//
//            // 存在serial_no 是通过接口同步过的,不需要管理
//            if ($model->serial_no > 0) {
//                continue;
//            }
//
//            // 卡号,姓名,算同一个人 只更改挂号状态
//            if ($model->truename == $item['InvalidName']) {
//                // 只更改状态
//                $model->state = $item['State'];
//                $model->serial_no = $item['SerialNo'];
//                $model->updated_time = time();
//                $model->save();
//            }
//        }
//    }
//
//    /**
//     * @apiName 同步更新,白友的 serial_no 和状态,不存在的添加
//     * @apiGroup
//     * @apiParam {Number}
//     * @apiParam {String}
//     * @author loujie
//     */
//    public static function updateSerialNo($hospital)
//    {
//        RegistrationList::$pix = $hospital;
//
//        $allUser = RegistrationList::find()
//            ->where(['>','serial_no',0])
//            ->asArray()
//            ->all();
//        $project_id = self::getProject($hospital);
//
//        foreach ($allUser as $item) {
//            //判断白友 相同卡号有没有serial_no,有就跳过
//            $model = User::find()
//                ->where([
//                    'project_id' => $project_id,
//                    'patient_card_id' => $item['card_id']
//                ])
//                ->one();
//
//            if (!$model) {
//                continue;
//            }
//            // serinal_no > 0 的 跳过
//            if ($model->serial_no > 0) {
//                continue;
//            }
//            // 卡号姓名 一致默认是同一个人  更新serial_no 更新status
//            if ($model->name = $item['truename'])
//            {
//                if ($item['state'] == 200) {
//                    $model->status = 1;
//                } else {
//                    $model->status = -1;
//                }
//
//                $model->serial_no = $item['serial_no'];
//                $model->save();
//            }
//        }
//    }
//
//    public static function diseases()
//    {
//        // 先获取,病种错误的
//        $sql1 = 'select *from by_patient_user where patient_diseases_id > 3 and patient_diseases_child_id = 0 group by patient_diseases_id';
//        $data = Yii::$app->db->createCommand($sql1)->queryAll();
//
//        foreach ($data as $item) {
//
//            // 先从老病种表 获取 旧的对应关系,获取 病名
//            $sql2 = 'select *from by_base_patient_diseases_合并删除前备份 where id = '.$item['patient_diseases_id'];
//            $data2 = Yii::$app->db->createCommand($sql2)->queryOne();
//
//            if ($data2['diseases_name'] == '其他') {
//                continue;
//            }
//
//            $patient_diseases_id = 0;
//            $patient_diseases_child_id = 0;
//
//            if ($data2['diseases_name'] == '廯类'){
//                $patient_diseases_id = 3;
//                $patient_diseases_child_id = 56;
//
//            }elseif($data2['diseases_name'] == '结节性痒疹') {
//                $patient_diseases_id = 3;
//                $patient_diseases_child_id = 25;
//            }else {
//                // 从新的病种表,根据病名获取,对应关系
//                $sql3 = "select *from by_base_patient_diseases where diseases_name = '$data2[diseases_name]'";
//                $data3 = Yii::$app->db->createCommand($sql3)->queryOne();
//                $patient_diseases_id = $data3['pid'];
//                $patient_diseases_child_id = $data3['id'];
//            }
//          Yii::$app->db->createCommand()->update('by_patient_user', ['patient_diseases_id' => $patient_diseases_id , 'patient_diseases_child_id' => $patient_diseases_child_id], [ 'patient_diseases_id' => $item['patient_diseases_id']  ,'patient_diseases_child_id' => 0])->execute();
//        }
//
//    }


//    public static function linshi($hospital)
//    {
//        $month_start = strtotime('2020-03-01');
//        $month_end = strtotime("+1 month -1 seconds", $month_start);
//
//        $feuzhen = self::getOutpatientType($hospital,'referral');
//        $loss = self::getOutpatientType($hospital,'loss');
//        $consulting = self::getOutpatientType($hospital,'advisory');
//
////        $outpatientArray = [];
////        $feuzhen ?  $outpatientArray[] = $feuzhen : false;
////        $loss ?  $outpatientArray[] = $loss : false;
//        // 查询挂号时间在 3月份 查询
//        $patientArray = User::find()
//            ->select('id,reg_time,patient_card_id,outpatient_type_id')
//            ->where(['and',
//                ['project_id' => self::getProject($hospital)],
//                ['between','reg_time', $month_start, $month_end],
//                ['<','last_revisiting_time',$month_end + 1],
//                ['<','last_clinic_time',$month_end + 1],
//                ['!=','outpatient_type_id',$consulting],
//                ['is_anti_relapse' => User::IS_ANTI_RELAPSE_NO],
//                ['status' => User::STATUS_ENABLE],
//            ])
//            ->asArray()
//            ->all();
//
//        $lossOrVisit = array_column($patientArray,'outpatient_type_id','patient_card_id');
//
//        // 查询新挂号用户该月消费信息
//        $cardArray = array_column($patientArray,'patient_card_id');
//        // 查询白友by_patient_consumption
//        $consumptionArray = Consumption::find()
//            ->select([
//                'sum(reality_money) as money,patient_card_id'
//            ])
//            ->where(['and',
//                ['project_id' => self::getProject($hospital)],
//                ['patient_card_id' => $cardArray],
//                ['between','clinic_time', $month_start, $month_end]
//            ])
//            ->groupBy('patient_card_id')
//            ->asArray()
//            ->all();
//
//        //查询流失金额底线
//        $leastMoney = self::getConfig('global_loss_amout_money',$hospital);
//
//        // 产生消费的用户
//        $consumptionPatient = array_column($consumptionArray,'patient_card_id');
//        // 查询挂号,且没有消费信息的用户
//        $diffArray = array_diff($cardArray,$consumptionPatient);
//
//        foreach ($diffArray as $value) {
//            $temp['patient_card_id'] = $value;
//            $temp['money'] = 0;
//            $consumptionArray[] = $temp;
//        }
//
//
//        $showArray = [];
//        // 查询患者三月份是否达标
//        $lossArray = [];
//        $visitArray = [];
//        foreach ($consumptionArray as $item) {
//
//            if ($item['money'] > $leastMoney && $lossOrVisit[$item['patient_card_id']] != $feuzhen) {
//                $item['old_outpatient_type_id'] = $lossOrVisit[$item['patient_card_id']];
//                $item['new_outpatient_type_id'] = $feuzhen;
//                $visitArray[] = $item['patient_card_id'];
//                $showArray[] = $item;
//            } elseif($item['money'] < $leastMoney && $lossOrVisit[$item['patient_card_id']] != $loss) {
//                $item['old_outpatient_type_id'] = $lossOrVisit[$item['patient_card_id']];
//                $item['new_outpatient_type_id'] = $loss;
//                $lossArray[] = $item['patient_card_id'];
//                $showArray[] = $item;
//            }
//
//        }
////         print_r($showArray);die();
//
//        User::updateAll(['outpatient_type_id' =>$feuzhen],['project_id' => self::getProject($hospital),'patient_card_id' => $visitArray]);
//        User::updateAll(['outpatient_type_id' =>$loss],['project_id' => self::getProject($hospital),'patient_card_id' => $lossArray]);
//
//    }
//
//
//    public static function linshi2($hospital)
//    {
//
//        $visit = self::getOutpatientType($hospital,'referral');
//        $loss = self::getOutpatientType($hospital,'loss');
//        $first = self::getOutpatientType($hospital, '初诊');
//        $duan = self::getOutpatientType($hospital, '断诊');
//        $consulting = self::getOutpatientType($hospital,'advisory');
//
//        $therapy_day =  self::getConfig('global_no_therapy_time',$hospital);
//
//        $therapy_time = time() - $therapy_day * 60 * 60 * 24;
//
//        $modelArray =  User::find()
//            ->select('id,patient_card_id,reg_time,last_revisiting_time,last_clinic_time,is_anti_relapse')
//            ->where(['project_id' => self::getProject($hospital),'outpatient_type_id' => 0])
//            ->asArray()
//            ->all();
//
//        $tempArray = [];
//
//        $month_start = strtotime(date('Y-m-01'));
//
//        foreach ($modelArray as $item)
//        {
//
//            if ($item['reg_time'] > $month_start) { //挂号时间在当月内的全部变成初诊
//                $outpatient_type_id = $first;
//                $outpatient_type_name = '初诊';
//
//            } elseif($item['reg_time'] < $therapy_time && $item['last_revisiting_time'] < $therapy_time && $item['last_clinic_time'] < $therapy_time ) { // 规定时间内没有来源信息的算断诊
//
//                $outpatient_type_id = $item['last_revisiting_time'] ? $visit : $duan;
//                $outpatient_type_name = $item['last_revisiting_time'] ? '复诊' : '断诊';
//
//            } elseif($item['reg_time'] < $therapy_time && ( $item['last_revisiting_time'] > $therapy_time || $item['last_clinic_time'] > $therapy_time) ){
//
//                $outpatient_type_id = $visit;
//                $outpatient_type_name = '复诊';
//            } else{
//                $outpatient_type_id = '';
//                $outpatient_type_name = '';
//                continue;
//            }
//
//
//            User::updateAll(['outpatient_type_id' => $outpatient_type_id],['id' => $item['id']]);
//
////            $tempArray[] = [
////                'project_id' => self::getProject($hospital),
////                'outpatient_type_id' =>$outpatient_type_id,
////                'outpatient_type_name' => $outpatient_type_name,
////                'patient_card_id' => $item['patient_card_id'],
////                'id' => $item['id'],
////            ];
//        }
//
//     //   print_r($tempArray);die();
//
//    }

    /**
     * @apiName
     * @apiGroup
     * @apiParam {Number}
     * @apiParam {String}
     * @author loujie
     */
    public static function dengtaPatientUser($params)
    {
        $url = Yii::$app->params['dengta_host'] . '/v1/patient/index/query-patient?name_sx=' . $params['name_sx'] . '&mobile=' . $params['mobile'] . '&clinic_name=' . $params['clinic_name'] . '&revisiting_time=' . $params['revisiting_time'];
        CommonHelper::https_request($url);
    }

}




